Skip to content
NewBun 1.4.5 is out. Release notes
AphrodyBun

Linter · Rules

react-hooks/purity

Disallow calls such as Math.random() and Date.now() while a component renders

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

Reported:

function Clock() {
  const now = Date.now();
  return <time>{now}</time>;
}
function Field({ label }) {
  const id = Math.random();
  return <input id={id} aria-label={label} />;
}

Not reported:

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} />;
}