Sub topic 15
Lazy initial state for expensive setup
This chapter assumes you know how useState works, how a re-render happens, and basic JavaScript such as arrow functions and JSON.parse.
The cost hidden in the initial value
useState(initialValue) uses its argument only on the first render. On every later render, React ignores it. The expression is still evaluated each time the component function runs, though.
import { useState } from 'react';
function Cart() {
// Runs on every render, but only the first result is used.
const [items, setItems] = useState(readCart());
return <p>{items.length} items</p>;
}If readCart() reads localStorage and parses JSON, that work repeats on each render and its result is thrown away. For a cheap value such as 0 or '', this does not matter. For expensive setup, it adds up.
Pass a function instead
Give useState a function and React calls it once, during the first render. It stores the return value as the initial state. This is called a lazy initializer.
import { useState } from 'react';
function Cart() {
const [items, setItems] = useState(() => {
const saved = localStorage.getItem('cart');
return saved ? JSON.parse(saved) : [];
});
return <p>{items.length} items</p>;
}On later renders React skips the function entirely, so storage is read and parsed once.
Pass the function, do not call it
The most common mistake is passing the result of a call instead of the function itself.
| Code | Behavior |
|---|---|
| `useState(readCart())` | `readCart` runs on every render. |
| `useState(readCart)` | React calls `readCart` once. |
| `useState(() => readCart())` | React calls the arrow function once. |
useState(readCart) works because React calls whatever function it receives, with no arguments. If your function needs arguments, wrap it in an arrow function: useState(() => buildBoard(size)).
When to use it
Use a lazy initializer when computing the starting value is noticeably costly:
- Reading and parsing
localStorage. - Building a large array or grid.
- Running a loop or filter over a big props list.
Do not use it for literals or cheap expressions like useState(0) or useState([]). The function adds noise and saves nothing.
Lazy initial state is not a lazy setter
A function passed to setItems is an updater function, covered earlier. It receives the previous state. A function passed to useState takes no arguments and runs once. Both accept functions, but they run at different times and for different reasons.
Exercise
A component calls const [grid, setGrid] = useState(createGrid(100));, where createGrid is slow. The component re-renders often, and it feels sluggish. What is the cause, and how do you fix it?
Show answer
React ignores the argument after the first render, but createGrid(100) is still evaluated on every render. Pass a function so React calls it only once: useState(() => createGrid(100)).