Skip to content
Tutorials Center
My learning

Topics

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.

JSX
const [state, dispatch] = useReducer(reducer, initialArg, init);

Try it

Initial state built from a prop
Building a board with init

Syntax

JSX
useReducer(reducer, initialArg, init)
TypeScript
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's key to start over, or handle it with a 'reset' action.
  • Reset pattern: exporting init and returning init(action.start) from the reducer keeps the reset logic identical to the mount logic.
  • Purity: StrictMode calls init twice 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.
  • useState has the same optimization through a lazy initializer.