Sub topic 8
Lazy initial state
This chapter covers the third argument of useReducer, the init function. It assumes you can write a reducer, dispatch actions, and read a basic useReducer component. It also assumes you know the useState lazy initializer form, useState(() => compute()). The chapter explains what init does, when it helps, how it supports resets, and the mistakes people make with it.
The problem: initial state that costs something
The simplest form of the hook takes a reducer and a ready-made initial state:
const [state, dispatch] = useReducer(reducer, { count: 0 });That is fine when the initial state is a small literal. Sometimes it is not. You may need to build a long list, parse a saved string, or read from localStorage. If you write the computation inline as the second argument, it looks like this:
const [state, dispatch] = useReducer(reducer, createInitialState(username));React only uses that value on the first render. But createInitialState(username) is an ordinary function call in your component body, so JavaScript runs it on every render. React throws the result away on every render after the first. If the function is expensive, you pay for it each time for nothing.
The useReducer signature has a third parameter to avoid this:
useReducer(reducer, initialArg, init?)When you pass init, React calls init(initialArg) once, during the first render, and uses the return value as the initial state. On later renders React does not call init again.
The three-argument form
The second argument changes meaning depending on whether you pass a third one.
| Call | What React uses as initial state |
|---|---|
| `useReducer(reducer, initialState)` | `initialState` itself |
| `useReducer(reducer, initialArg, init)` | The result of `init(initialArg)`, computed once |
Here is the counter from earlier chapters rewritten with an init function:
import { useReducer } from 'react';
function init(initialCount) {
return { count: initialCount };
}
function reducer(state, action) {
switch (action.type) {
case 'incremented':
return { count: state.count + 1 };
case 'reset':
return init(action.payload);
default:
throw Error('Unknown action: ' + action.type);
}
}
export default function Counter({ initialCount }) {
const [state, dispatch] = useReducer(reducer, initialCount, init);
return (
<>
<p>{state.count}</p>
<button onClick={() => dispatch({ type: 'incremented' })}>+1</button>
<button onClick={() => dispatch({ type: 'reset', payload: initialCount })}>
Reset
</button>
</>
);
}Three details are worth noticing:
initreceivesinitialCount, which is the value of the second argument. It does not receive props or any other values from the component.- You pass the function itself,
init, not a call to it. Writinginit(initialCount)as the third argument would pass the returned object, and React would then try to call that object as a function. - The
resetcase reusesinit. The reducer defines what "initial" means in one place, so a reset cannot drift away from the real starting state.
How the first render uses init
The diagram shows the order of events on the first render and on later ones.
After the first render, init is out of the picture unless your own code calls it, as the reset case above does.
A realistic example: expensive setup
Suppose a to-do app seeds a list from a username. The seed function loops and builds objects, so you do not want it to run on every keystroke.
import { useReducer } from 'react';
function createInitialState(username) {
const todos = [];
for (let i = 0; i < 50; i++) {
todos.push({ id: i, text: username + "'s task #" + (i + 1), done: false });
}
return { draft: '', todos };
}
function reducer(state, action) {
switch (action.type) {
case 'draft_changed':
return { ...state, draft: action.value };
case 'reset':
return createInitialState(action.username);
default:
throw Error('Unknown action: ' + action.type);
}
}
export default function TodoSeed({ username }) {
const [state, dispatch] = useReducer(reducer, username, createInitialState);
return (
<>
<input
value={state.draft}
onChange={e => dispatch({ type: 'draft_changed', value: e.target.value })}
/>
<button onClick={() => dispatch({ type: 'reset', username })}>Reset</button>
<p>{state.todos.length} tasks, first: {state.todos[0].text}</p>
</>
);
}Each keystroke triggers a re-render. With the three-argument form, createInitialState ran once at mount and does not run again on those renders. With the one-argument form, createInitialState(username) would run 50 iterations on every keystroke.
Reading saved data on startup
A common use of init is restoring state from localStorage. The read is synchronous, so it can supply the initial state directly.
import { useEffect, useReducer } from 'react';
const STORAGE_KEY = 'notes';
function loadState(key) {
try {
const saved = window.localStorage.getItem(key);
return saved ? JSON.parse(saved) : { notes: [] };
} catch {
return { notes: [] };
}
}
function notesReducer(state, action) {
switch (action.type) {
case 'added':
return { notes: [...state.notes, { id: action.id, text: action.text }] };
case 'cleared':
return { notes: [] };
default:
throw Error('Unknown action: ' + action.type);
}
}
export default function Notes() {
const [state, dispatch] = useReducer(notesReducer, STORAGE_KEY, loadState);
useEffect(() => {
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
}, [state]);
return (
<>
<button
onClick={() =>
dispatch({ type: 'added', id: Date.now(), text: 'Note ' + (state.notes.length + 1) })
}
>
Add note
</button>
<button onClick={() => dispatch({ type: 'cleared' })}>Clear</button>
<ul>
{state.notes.map(n => (
<li key={n.id}>{n.text}</li>
))}
</ul>
</>
);
}Two points about this code:
loadStatecatches errors.JSON.parsethrows on corrupt data, andlocalStorageitself can throw when storage is blocked. A crash during initialization would break the component on mount.- Saving happens in
useEffect, not in the reducer. Writing to storage is a side effect, and reducers must stay pure.
The next section explains why the purity rule applies to init as well.
init must be pure
React treats init like the reducer: it should compute its result from its argument and nothing else. In development, Strict Mode calls your initializer function twice and discards one of the results, to expose impurities. The reducer gets the same treatment.
Several things are safe in init:
- Reading a value from
localStorage, since reading does not change anything. - Building arrays and objects from the argument.
- Parsing JSON.
Several are not:
- Writing to
localStorageor any external store. - Calling
Math.random()orDate.now()when you expect the same result each time. With Strict Mode's double call, the two results would differ and you would only notice in development. Generating an id once at mount is acceptable if you accept that, but tests that expect a fixed output will fail. - Mutating objects that live outside
init, such as a module-level array. - Dispatching actions or setting state.
If you see an effect twice in the console from init, such as a doubled log line, it is Strict Mode doing its check. It does not happen in production builds.
initialArg changes are ignored after mount
React reads initialArg and runs init on the first render only. If the prop that feeds it changes later, the state does not follow:
function Profile({ userId }) {
// loadProfile(userId) runs once. If userId changes, state stays as it was.
const [state, dispatch] = useReducer(profileReducer, userId, loadProfile);
// ...
}You have two ways to handle this:
- Give the component a
keythat includesuserId, as in<Profile key={userId} userId={userId} />. React then discards the old instance and mounts a new one, which runsinitagain. This is usually the cleanest choice. - Add a reducer case, such as
'user_changed', and dispatch it from an event handler. Dispatching from an effect after render works too, but costs an extra render with stale state.
Do not try to sync by calling init yourself during render. That reintroduces the cost you were avoiding and can cause render loops.
Using init for reset
The counter example showed the main idiom: the reducer calls init(action.payload) for a reset action. There is a subtlety. The reducer does not receive initialArg on its own. It only gets state and action, so you pass the value through the action payload, as payload: initialCount does.
Do not capture the prop inside the reducer by defining the reducer inside the component. That creates a new reducer function on each render, which works but obscures where state logic lives, and makes the reducer harder to test and move out of the file. Keep the reducer at module scope and send what it needs through the action.
Choosing between the forms
Use the plain two-argument form when the initial state is a cheap literal:
const [state, dispatch] = useReducer(reducer, { count: 0 });Reach for init when one of these is true:
- Computing the initial state costs real work, such as loops, parsing, or large allocations.
- You want a single
initfunction that both starts and resets the state. - The initial state depends on a prop and you want the dependency to be explicit.
Do not use init just to look advanced. For a one-field object it adds a function and an argument with no benefit.
Common errors
- Passing a call instead of a function.
useReducer(reducer, arg, init(arg))hands React the result ofinit. React then tries to call that result as a function, and you get an error like "init is not a function". Writeinit, notinit(arg). - Expecting
initto run on updates. It runs once. Usekeyor a reducer case to react to changes. - Side effects in
init. Writing to storage or logging ininitwill run twice under Strict Mode. - Forgetting to share logic with reset. If
resetreturns a hard-coded object that differs frominit's result, the first render and a reset will disagree. - Mutating the argument. If
initmodifiesinitialArg, which might be a prop or shared object, you break the immutability rules from earlier chapters.
Exercise
A component calls useReducer(reducer, buildBoard(size)), where buildBoard creates a 100x100 grid. The component re-renders on every mouse move, and profiling shows buildBoard running each time. Rewrite the call so it runs once, and explain how you would implement a "new game" button that resets the board without storing size inside the reducer.
Show answer
Change the call to useReducer(reducer, size, buildBoard). React then calls buildBoard(size) only on the first render. For the button, keep the reducer at module scope and add a 'new_game' case that returns buildBoard(action.size). The button dispatches { type: 'new_game', size }, so the reducer receives size through the action payload and reuses the same function that created the initial state. Passing buildBoard(size) as the third argument would be wrong because it passes the finished grid, not a function.
Exercise
A Editor component takes a documentId prop and uses useReducer(editorReducer, documentId, loadDocument). When the parent switches documentId from "a" to "b", the editor keeps showing document "a". Why does this happen, and what is the smallest change that fixes it?
Show answer
React runs init only on the first render, so a later change to documentId does not recompute the state. The smallest fix is in the parent: render <Editor key={documentId} documentId={documentId} />. A new key makes React unmount the old instance and mount a fresh one, which calls loadDocument with the new id. A reducer case such as 'document_changed' also works, but it needs a dispatch at the right moment and more code.