Skip to content

Components and Hooks must be pure: the useTime example still runs new Date() during render #8777

Backlog

Description

@omollohzack

The "Components and Hooks must be pure" page says all code that runs during render must be idempotent, and it calls const time = new Date() in a component bad for that reason. It then fixes the example by synchronizing with an Effect, and the fixed useTime hook reads:

const [time, setTime] = useState(() => new Date());

The comment on the interval line says "✅ Good: non-idempotent code no longer runs in render", and the text below the example says: "By wrapping the non-idempotent new Date() call in an Effect, it moves that calculation outside of rendering."

But the initializer still runs new Date() during render. React calls the initializer function when initializing the component, on the initial render — and the useState reference in this same repo says an initializer function "should be pure", and that in Strict Mode React calls it twice to help find accidental impurities. new Date() is not pure: it returns a different value on each call. So the example breaks the rule the page is teaching, and the claim that the non-idempotent code no longer runs in render is not accurate — only the updates moved into the Effect. The first value still comes from a non-idempotent call during render.

Possible fixes: set the initial time inside the Effect as well (for example, start as null and set it on mount), so no new Date() runs in render at all. Or keep the example but change the wording, so the page does not claim the call no longer runs in render, and notes the initializer as an exception. The first option keeps the page consistent with the useState reference.

I am reporting the useTime example on this page only.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions