Sub topic 15
Lazy initial state for expensive setup
This chapter assumes you can declare state with useState, you know that a component function runs again on every render, and you are comfortable with arrow functions. It covers one narrow feature: passing a function to useState so that expensive setup work runs once instead of on every render.
The problem: the initial value is computed every render
useState(initialValue) uses its argument only on the first render. On later renders React ignores it and returns the stored state. The argument is still an expression, though, and JavaScript evaluates it before useState is called. That happens on every render.
import { useState } from 'react';
function createInitialTodos() {
console.log('createInitialTodos ran');
const todos = [];
for (let i = 0; i < 1000; i++) {
todos.push({ id: i, text: `Task ${i}`, done: false });
}
return todos;
}
function TodoApp() {
const [todos, setTodos] = useState(createInitialTodos());
const [text, setText] = useState('');
return (
<>
<input value={text} onChange={e => setText(e.target.value)} />
<p>{todos.length} todos</p>
</>
);
}Every keystroke updates text, which re-renders TodoApp. Each render calls createInitialTodos() again and builds 1000 objects. React then throws the result away, because todos already exists. The console log shows the waste. The output is correct, but the work is repeated.
The fix: pass a function
If you pass a function to useState, React calls it only during the first render and uses the return value as the initial state. This form is called a lazy initializer. The only change is dropping the parentheses.
import { useState } from 'react';
function createInitialTodos() {
console.log('createInitialTodos ran');
const todos = [];
for (let i = 0; i < 1000; i++) {
todos.push({ id: i, text: `Task ${i}`, done: false });
}
return todos;
}
function TodoApp() {
const [todos, setTodos] = useState(createInitialTodos);
const [text, setText] = useState('');
return (
<>
<input value={text} onChange={e => setText(e.target.value)} />
<p>{todos.length} todos</p>
</>
);
}Now createInitialTodos runs once, when the component mounts. You pass the function itself, not its result. React decides whether to call it.
Reading from storage
The most common real use is restoring saved data. localStorage.getItem is synchronous, and JSON.parse has to process the whole string. Doing both on every render is wasteful.
import { useState } from 'react';
function readCart() {
const saved = localStorage.getItem('cart');
return saved ? JSON.parse(saved) : [];
}
function Cart() {
const [items, setItems] = useState(readCart);
function addItem(name) {
const next = [...items, name];
setItems(next);
localStorage.setItem('cart', JSON.stringify(next));
}
return (
<>
<button onClick={() => addItem('Apple')}>Add apple</button>
<p>{items.length} items</p>
</>
);
}The save happens in the event handler, next to the state update. Reload the page and the cart comes back, because readCart runs once on mount and reads what the handler saved.
When you do not need it
A lazy initializer adds a small amount of syntax. Use it only when the initial value is costly to produce.
| Initial value | Use a function? |
|---|---|
| `0`, `''`, `false`, `null` | No. Literals cost nothing. |
| `[]` or `{}` | No. Allocating an empty object is trivial. |
| `props.initialCount` | No. Reading a property is cheap. |
| `items.filter(...)` over a large array | Yes |
| `JSON.parse(localStorage.getItem(...))` | Yes |
| Building a large grid, tree, or lookup table | Yes |
If you are unsure, measure first. For most components the difference is not noticeable.
Rules for the initializer
React expects the initializer to follow a few rules.
- It takes no arguments. React calls it with none. If you need a value from props, close over it:
useState(() => buildBoard(props.size)). - It must be pure. It should compute a result from its inputs and change nothing outside itself. Do not send network requests or start timers in it.
- It must return the initial state. A missing
returnin a block-bodied arrow function gives youundefinedstate.
In development, React Strict Mode deliberately calls initializer functions twice and keeps one result. This exposes impurity. If your initializer logs twice in development but once in production, that is expected. If the two calls produce different outcomes that matter, the function is not pure.
Updater functions and function-valued state
The lazy initializer looks like the updater form from earlier in the tutorial, and both treat a function argument specially. They are different features in different places. The initializer is the argument to useState. An updater is the argument to the setter. Neither is called with the other's inputs.
| Row | Where it goes | React calls it | Receives |
|---|---|---|---|
| Lazy initializer | `useState(fn)` | Once, on first render | Nothing |
| Updater function | `setState(fn)` | On each update | The latest pending state |
Treating functions specially has a side effect. If you want to store a function as state, passing it directly makes React call it. Wrap it in another function.
import { useState } from 'react';
function Calculator() {
const [operation, setOperation] = useState(() => (a, b) => a + b);
return (
<>
<p>2 and 3 gives {operation(2, 3)}</p>
<button onClick={() => setOperation(() => (a, b) => a * b)}>
Multiply
</button>
</>
);
}The outer function in each case is consumed by React. The inner function becomes the stored value. Storing functions in state is unusual, so check whether you could store a name such as 'add' and look up the function during render instead.
The initial value is still only initial
Lazy initialization does not make state follow its source. If the initializer reads a prop, the result is captured once.
import { useState } from 'react';
function Editor({ initialText }) {
const [text, setText] = useState(() => initialText.trim());
return <textarea value={text} onChange={e => setText(e.target.value)} />;
}If the parent later passes a different initialText, Editor keeps showing the old text. That is the intended behavior, and the prop name signals it. When you need the component to start over for new input, give it a key, as covered in the chapter on state identity. When the value should always track the prop, do not copy it into state. Compute it during render.
Server rendering
Initializers also run when a component renders on a server. There, localStorage and window do not exist, so readCart above would throw a ReferenceError. In a server-rendered app, guard the access with typeof window !== 'undefined'. Even then, the server and the browser can produce different first renders, which causes hydration mismatches. Frameworks usually offer a safer pattern for browser-only data. In a client-only app, such as one built with Vite and rendered entirely in the browser, this concern does not apply.
Exercise
A component calls const [grid, setGrid] = useState(buildGrid(100)). buildGrid creates a 100 by 100 array and logs a message. The component re-renders each time the user types in an unrelated input. How many times does the message log after the component mounts and the user types 5 characters, and what change makes it log once?
Show answer
It logs 6 times: once on mount and once for each of the 5 re-renders. buildGrid(100) is evaluated on every render even though React ignores the result after the first one. Change the call to useState(() => buildGrid(100)). React then calls the arrow function only on the first render, so the message logs once. In development with Strict Mode, expect two logs on mount because React calls initializers twice to check purity.
Exercise
Why does useState(() => ({ name: props.name })) differ from useState({ name: props.name }) in cost, and does either one keep name in sync when props.name changes?
Show answer
The function form builds the object only on the first render. The direct form builds a new object on every render and discards it, though for a small object this cost is negligible, so the lazy form gains almost nothing here. Neither form keeps name in sync. State is set from the initial value once, and later changes to props.name do not affect it unless the component remounts, for example through a changed key.