liveBook · Manning

useReducer initialization function

As explained in React Hooks in Action: With Suspense and Concurrent Mode

A useReducer initialization function is an optional function that computes the initial reducer state from an initialization argument.

A useReducer initialization function computes a reducer’s initial state from an initialization argument. Pass the reducer, argument, and function as the three useReducer arguments; React calls the function on the hook’s first call. section 3.3 section 3.5

Use the pattern when initial-state creation needs an input or reusable computation:

  • const [state, dispatch] = useReducer(reducer, initArgument, initFunction); section 3.3
  • React passes initArgument to initFunction, uses its return value as the initial state, and returns state with a dispatch function. section 3.3
  • Prefer the function when state generation is expensive or when an existing utility can generate the state. section 3.3.4 section 3.5

Initialize a week picker from a date

A WeekPicker receives a date prop and derives its initial week with a reusable date utility: const [week, dispatch] = useReducer(reducer, date, getWeek); The returned week becomes reducer state, while dispatch handles actions such as PREV_WEEK and TODAY. section 3.3.4 section 3.3.5

const [state, dispatch] = useReducer(reducer, initArgument, initFunction);

Shows the three-argument useReducer form that connects the initialization argument to the initialization function. section 3.3

How React Hooks in Action: With Suspense and Concurrent Mode covers it

How deep it goes
Explains the three-argument call, argument flow, initial return value, and one-time expensive generation without covering implementation internals.
Examples
Uses a WeekPicker, a date prop, getWeek, and PREV_WEEK, TODAY actions to demonstrate derived initial state and navigation.
What it assumes
Assumes familiarity with reducers and useReducer while establishing how initialization arguments produce initial state.
What you can do after
Build reducer state initialization from an argument and reuse or defer expensive state-generation work until the hook’s first call.
How it connects
Connects initialization functions with useReducer, reducers, initial state, dispatch functions, props, and useState initialization.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React Hooks in Action: With Suspense and Concurrent Mode. The section links point to the parts of the book it draws on.