Skip to content
Tutorials Center
My learning

Topics

React Reference ยท State Hooks

React useState lazy initialization

Reference for lazy initial state in React useState: pass a function so an expensive computation runs only on the first render, not on every render.

The initial value you give useState is only used on the first render, but if you write it as an expression, JavaScript evaluates it on every render and React throws the result away. When that expression is expensive (parsing a big string, building a large grid), pass a function instead. React calls it once, during the first render, and ignores it afterwards.

This is called lazy initialization. The function is an initializer: it takes no arguments and returns the initial state.

JSX
const [grid, setGrid] = useState(() => buildGrid(50));   // runs once
const [grid2, setGrid2] = useState(buildGrid(50));       // buildGrid runs every render

Try it

Counting how often work happens

The eager counter grows with every render; the lazy counter stays at its first value. (Both run twice during the very first render if you wrap the tree in StrictMode in development.)

Parsing a value once

Syntax

JSX
const [state, setState] = useState(() => computeInitial());
TypeScript
function useState<S>(initializer: () => S): [S, Dispatch<SetStateAction<S>>];
Name Description
initializer A pure function with no parameters. Its return value becomes the initial state.

Returns: the same [state, setState] pair as the plain form.

Edge cases: the initializer must be called by React. useState(compute()) passes the result of calling it (no laziness); useState(compute) passes the function itself, which is lazy and works when compute takes no arguments.

Usage notes

  • Pass the function, don't call it. useState(() => load(id)) is lazy; useState(load(id)) is not. A frequent bug is writing the call inside the parentheses.
  • Only the first render matters. If id changes later, the initializer does not re-run, and state keeps its old value. To reset state when a prop changes, give the component a key.
  • Keep it pure. StrictMode calls the initializer twice in development to catch side effects. Do not read from or write to external systems that must happen exactly once.
  • Cheap values don't need it. useState(0), useState('') and useState([]) cost nothing; lazy form adds noise.
  • Reading storage: an initializer is a natural place to read saved settings, but localStorage is unavailable in the sandboxed examples on this site, so those reads are shown read-only elsewhere.
  • A function is not a stored value. Because React treats a function argument as an initializer, you cannot store a function directly. Wrap it: useState(() => myCallback).
  • Same idea in useReducer with its third argument.