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
