react-hooks/purity
Disallow calls such as Math.random() and Date.now() while a component renders
Also called react_hooks/purity, react/purity
React can render a component more than once for one update, and it can reuse an earlier result. So a component must return the same output for the same props and state. A call that returns a new value each time breaks that. The id, the time, or the random number changes on every render, and the server and the browser disagree during hydration.
The rule reports Math.random(), Date.now(), and performance.now() in the body of a component or a hook. Calls in event handlers and effects are fine, because they don't run during render.
With an oxlint config, the rule also reports new Date() and Date() without arguments.
Configure#
Off by default. To turn it on:
[lint.rules]
"react-hooks/purity" = "error" # or "warn"Examples#
function Clock() {
const now = Date.now()Error: Cannot call impure function during renderDate.now is an impure function. Calling an impure function can produce unstable results that update unpredictably when the component happens to re-render. (react.dev/reference/rules/components-and-hooks-must-be-pure#components-and-hooks-must-be-idempotent).;
return <time>{now}</time>;
}function Field({ label }) {
const id = Math.random()Error: Cannot call impure function during renderMath.random is an impure function. Calling an impure function can produce unstable results that update unpredictably when the component happens to re-render. (react.dev/reference/rules/components-and-hooks-must-be-pure#components-and-hooks-must-be-idempotent).;
return <input id={id} aria-label={label} />;
}import { useEffect, useId, useState } from "react";
function Clock() {
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
const timer = setInterval(() => setNow(Date.now()), 1000);
return () => clearInterval(timer);
}, []);
return <time>{now}</time>;
}
function Field({ label }) {
const id = useId();
return <input id={id} aria-label={label} />;
}