React Reference ยท State Hooks
React useReducer init function
Reference for the optional third argument of React useReducer: an init function that builds the initial state once, and how to reuse it for reset actions.
useReducer accepts an optional third argument, init. When you pass it, React does not use the second argument as the state. It calls init(initialArg) once, during the first render, and uses the return value as the initial state.
This avoids rebuilding a big initial state on every render, and it gives you a clean way to implement a "reset" action: call init again with the same argument from inside the reducer.
const [state, dispatch] = useReducer(reducer, initialArg, init);
Try it
Syntax
useReducer(reducer, initialArg, init)
function useReducer<S, A, I>( reducer: (state: S, action: A) => S, initialArg: I, init: (arg: I) => S ): [S, Dispatch<A>];
| Name | Description |
|---|---|
initialArg |
The value handed to init. It is not stored as state itself. |
init |
A pure function that takes initialArg and returns the initial state. Called once per mounted component instance. |
Returns: the usual [state, dispatch].
Edge cases: when init is omitted, initialArg is the state. Passing init as undefined is the same as omitting it.
Usage notes
- Pass the function, don't call it.
useReducer(reducer, 3, buildBoard)is lazy.useReducer(reducer, buildBoard(3))builds the board on every render and discards it. - Called once per instance. Later changes to
initialArg(for example a new prop) are ignored. Change the component'skeyto start over, or handle it with a'reset'action. - Reset pattern: exporting
initand returninginit(action.start)from the reducer keeps the reset logic identical to the mount logic. - Purity: StrictMode calls
inittwice in development; keep it free of side effects. - When to skip it: if the initial state is a small literal,
useReducer(reducer, { count: 0 })is clearer. useStatehas the same optimization through a lazy initializer.