Sub topic 8
Lazy initial state
This chapter assumes you can write a reducer, dispatch actions, and call useReducer in a component. It covers the third argument to useReducer, the init function, and the mistakes that come with it.
The problem: initial state computed on every render
useReducer(reducer, initialArg) uses initialArg as the starting state on the first render only. If you build that value with an expression, the expression still runs on every render.
const [state, dispatch] = useReducer(reducer, createInitialState(username));React ignores the result of createInitialState(username) after the first render. The function call still happens each time, so an expensive computation is wasted work.
The init function
Pass a third argument to avoid this. React calls init(initialArg) once, during the first render, and uses the return value as the initial state.
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>
</>
);
}The component passes initialCount as the second argument and init as the third. React runs init(initialCount) once. The reducer's reset case calls the same init, so the starting shape lives in one place.
Pass the function, do not call it
The most common error is calling init yourself.
// Runs init on every render. The result is thrown away after the first.
useReducer(reducer, init(initialCount));
// Runs init once, on the first render.
useReducer(reducer, initialCount, init);Both versions give the same first state, so the bug is easy to miss. The first one only costs performance.
When lazy initialization is worth it
Use init when building the first state is expensive or reads from somewhere slow. Typical cases:
- Parsing data from
localStorage. - Building a large array or lookup table.
- Deriving the starting state from props through several steps.
For a cheap literal such as { count: 0 }, skip it. A plain second argument is clearer.
Using init to reset state
init also gives you a clean reset. The reset action in the example above carries the argument in its payload and passes it back to init. That avoids writing the starting shape twice, which prevents the reset state from drifting away from the initial state when you add a field.
Keep init pure
React may call init twice in development under Strict Mode, to help you find impure code. Treat it like the reducer: it should compute a value from its argument and do nothing else. Reading from localStorage is fine. Writing to it, or sending a request, is not.
Check your understanding
Exercise
A component contains useReducer(reducer, loadFromStorage(key)), and loadFromStorage parses a large JSON string. Rewrite the call so the parsing runs only on the first render, and say what you must change in loadFromStorage.
Show answer
Write useReducer(reducer, key, loadFromStorage). React then calls loadFromStorage(key) once, on the first render. loadFromStorage must accept key as its single parameter and return the initial state. It should stay pure, so reading from storage is fine but it must not write to storage.
Exercise
Your init function returns { count: initialCount, step: 1 }. The reset case in the reducer returns { count: 0 }. What goes wrong, and how do you fix it?
Show answer
After a reset, step is missing, so any code reading state.step gets undefined. The reset case duplicates the state shape and has fallen out of sync. Fix it by returning init(action.payload) from the reset case, so the shape is defined only in init.