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.
const [grid, setGrid] = useState(() => buildGrid(50)); // runs once const [grid2, setGrid2] = useState(buildGrid(50)); // buildGrid runs every render
Try it
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.)
Syntax
const [state, setState] = useState(() => computeInitial());
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
idchanges later, the initializer does not re-run, and state keeps its old value. To reset state when a prop changes, give the component akey. - 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('')anduseState([])cost nothing; lazy form adds noise. - Reading storage: an initializer is a natural place to read saved settings, but
localStorageis 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.