日本語

Fixing the react-hooks/purity Error for Date.now() in React

​​React​ESLint,Troubleshooting,TypeScript,useEffect,useState

If npx eslint reports "Cannot call impure function during render" from react-hooks/purity, your component calls Date.now() in its body during render. This often happens in components that show elapsed time, such as "posted N minutes ago," or the current time. To fix it, move Date.now() out of render. Get the first value with the useState(() => Date.now()) initializer function, and update it later with a timer in useEffect. If the value should match a user action, such as the time a button was pressed, call Date.now() inside the event handler.

I triggered the error on purpose in a test environment, copied the message as it appeared, and confirmed that the error disappears after the fix.

Note

The test environment was Ubuntu 24.04 with Node.js 22.23.5. I used react and react-dom 19.3.1, TypeScript 6.0.3, ESLint 10.16.0, eslint-plugin-react-hooks 7.1.1, and typescript-eslint 8.74.0. The ESLint configuration was the recommended presets from @eslint/js and typescript-eslint, plus the recommended preset from eslint-plugin-react-hooks (reactHooks.configs.flat.recommended). I checked the behavior in the browser by building the page for development with esbuild 0.28.2 and opening it in Chromium 158 with Playwright 1.63.0. I did not test the display inside editors such as VS Code, the ESLint setup in Next.js, or builds that use the React Compiler.

The full error message

For the test, I used the following component. It receives the posting time postedAt (in milliseconds) and shows "posted N minutes ago."

tsx
export function PostedAt({ postedAt }: { postedAt: number }) {
  const now = Date.now();
  const minutes = Math.floor((now - postedAt) / 60000);
  return <p>{minutes}分前に投稿</p>;
}

The type check (npx tsc) passes. When I ran npx eslint, it reported the following error. The block below shows only the part of the output for this file. I replaced the working directory path with /path/to/app.

text
/path/to/app/src/bad/PostedAt.tsx
  2:15  error  Error: Cannot call impure function during render

`Date.now` is an impure function. Calling an impure function can produce unstable results that update unpredictably when the component happens to re-render. (https://react.dev/reference/rules/components-and-hooks-must-be-pure#components-and-hooks-must-be-idempotent).

/path/to/app/src/bad/PostedAt.tsx:2:15
  1 | export function PostedAt({ postedAt }: { postedAt: number }) {
> 2 |   const now = Date.now();
    |               ^^^^^^^^^^ Cannot call impure function
  3 |   const minutes = Math.floor((now - postedAt) / 60000);
  4 |   return <p>{minutes}分前に投稿</p>;
  5 | }  react-hooks/purity

The message means that an impure function cannot be called during render. Date.now is impure. Calling it can produce unstable results, and the value can change unpredictably whenever the component happens to re-render. The severity is error, not warning, and npx eslint exited with code 1. When I checked the JSON output, it contained neither an automatic fix (fix) nor a suggestion (suggestions).

This rule is one of the rules that ESLint uses to report problems that the React Compiler detects. According to the eslint-plugin-react-hooks reference, it is included in the recommended preset and works even in apps that do not use the React Compiler. I did not use the React Compiler in this test.

What goes wrong when it is called during render

The official purity rule documentation says that a component must be a pure function that returns the same JSX for the same props. It also says that calling Date.now() during render changes the result on each render, which can cause hydration mismatches and prevent memoization from working correctly.

In my test, the problem appeared as a display that did not update. I opened the page five minutes after posting and used Playwright's clock control to advance the time.

text
読み込み直後 | bad: 5分前に投稿 | good: 5分前に投稿
1分後 | bad: 5分前に投稿 | good: 6分前に投稿
2分後 | bad: 5分前に投稿 | good: 7分前に投稿

bad is the code that produced the error above, and good is the code I fixed in the next section. After two minutes, the version that called Date.now() during render still showed "5 minutes ago." The display stayed frozen.

Two boxes stacked vertically. The text in the image is in Japanese. The top box is headed "Date.now() during render" and shows "5 minutes ago." The bottom box is headed "useState and useEffect" and shows "6 minutes ago."
The page one minute after load. The version that calls Date.now() during render still shows 5 minutes ago.

Take the initial value in a useState initializer and update it with a timer

I applied the same pattern as the clock example in the official purity rule documentation.

tsx
import { useEffect, useState } from 'react';

export function PostedAt({ postedAt }: { postedAt: number }) {
  const [now, setNow] = useState(() => Date.now());

  useEffect(() => {
    const id = setInterval(() => setNow(Date.now()), 60000);
    return () => clearInterval(id);
  }, []);

  const minutes = Math.floor((now - postedAt) / 60000);
  return <p>{minutes}分前に投稿</p>;
}

The current time is stored in the state variable now. The initial value comes from calling Date.now() inside the function passed to useState. After that, a timer in useEffect runs every minute and calls setNow(Date.now()). The initializer function runs only during the first render, and the timer callback runs outside render, so react-hooks/purity does not report an error.

npx eslint src/good --max-warnings 0 finished with no errors and no warnings. In the browser, the display increased by one minute at each tick, going from "6 minutes ago" to "7 minutes ago," as shown above. I opened the page wrapped in StrictMode, and the console showed no errors or warnings.

Point

When I passed the result of the call directly, as in useState(Date.now()), instead of passing a function, the same react-hooks/purity error appeared. Pass a function with () =>.

The useState reference on avoiding recreation of the initial state explains that when you pass a function, React calls it only during the first render. If you pass the value directly, Date.now() runs on every render, and React discards every result after the first.

For a time tied to a user action, call it in an event handler

For a value tied to a user action, such as the time a button was pressed, call Date.now() inside the event handler. Event handlers do not run during render, so they do not trigger the error.

tsx
import { useState } from 'react';

export function StampButton() {
  const [pressedAt, setPressedAt] = useState<number | null>(null);

  return (
    <>
      <button type="button" onClick={() => setPressedAt(Date.now())}>
        記録する
      </button>
      {pressedAt !== null && <p>{new Date(pressedAt).toLocaleTimeString('ja-JP')}に記録</p>}
    </>
  );
}

When I pressed the button in the browser, the page showed the pressed time, for example 10:02:00, followed by a "recorded" label. I set the Playwright clock to 10:00, advanced it by two minutes, and then pressed the button.

Calling setState right away in useEffect causes a different error

I also tried starting with 0 as the initial value and calling setNow(Date.now()) right away inside useEffect. This removes the react-hooks/purity error, but it causes a react-hooks/set-state-in-effect error instead.

tsx
const [now, setNow] = useState(0);

useEffect(() => {
  setNow(Date.now());
}, []);
text
/path/to/app/src/try/EffectSet.tsx
  7:5  error  Error: Calling setState synchronously within an effect can trigger cascading renders

The full message goes on to explain that calling setState synchronously inside an effect can cause cascading renders and hurt performance, so this pattern is discouraged. If you take the initial value in the useState initializer function, and call setNow only from a function that runs later, such as the timer callback, neither error appears.

Wrapping it in useMemo or useRef does not remove the error

Putting Date.now() inside useMemo, or using it as the initial value of useRef, also produced the react-hooks/purity error. Both run during render.

tsx
const minutes = useMemo(() => Math.floor((Date.now() - postedAt) / 60000), [postedAt]);
tsx
const startedAt = useRef(Date.now());
return <p>{startedAt.current}</p>;

With the useRef version, the line that reads startedAt.current during render also produced a react-hooks/refs error, "Cannot access refs during render."

Adding // eslint-disable-next-line react-hooks/purity directly above the line that calls Date.now() made the error go away. However, the code is unchanged from before the fix, and it still calls Date.now() during render.

new Date() and Date.now() inside another function are not reported

The official purity rule documentation lists common examples such as Math.random(), Date.now() and new Date(), crypto.randomUUID(), and performance.now(). In my test environment, however, the following two cases did not produce errors.

tsx
export function Today() {
  const today = new Date();
  return <p>{today.toLocaleDateString('ja-JP')}</p>;
}
tsx
function minutesSince(postedAt: number) {
  return Math.floor((Date.now() - postedAt) / 60000);
}

export function Helper({ postedAt }: { postedAt: number }) {
  const minutes = minutesSince(postedAt);
  return <p>{minutes}分前に投稿</p>;
}

Looking at the code of eslint-plugin-react-hooks 7.1.1, only three functions are marked impure: true: performance.now, Date.now, and Math.random. In this version, code that uses new Date() during render, or calls Date.now() inside a function outside the component, is not reported. The value still changes on every render, so when you find such code, move it into a useState initializer or an event handler in the same way.

​Posted by 86