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:

bunfig.toml
[lint.rules]
"react-hooks/purity" = "error" # or "warn"

Examples#

example.jsx1 problem
function Clock() {
  const now = Date.now();
  return <time>{now}</time>;
}
example.jsx1 problem
function Field({ label }) {
  const id = Math.random();
  return <input id={id} aria-label={label} />;
}
example.jsxNo problems
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} />;
}