init Function Signature and Arguments
You'll learn: How the init function receives useReducer's second parameter and transforms it into your initial state.
When you pass a third argument to useReducer, that function (the init function) doesn't just run blindly—it receives the second parameter you passed to useReducer as its only argument.
How the Flow Works
const [state, dispatch] = useReducer(reducer, initialArg, init);
Here's what happens:
- React calls
init(initialArg) - Whatever
initreturns becomes your initial state - The
initialArgcan be anything: a number, string, object, array
The Function Signature
function init(initialArg) {
// Transform initialArg into initial state
return computedInitialState;
}
The init function:
- Receives: The
initialArg(second parameter touseReducer) - Returns: The initial state object
Practical Example
function createInitialState(userId) {
return {
userId: userId,
profile: expensiveProfileLookup(userId),
settings: loadDefaultSettings(userId)
};
}
// userId is passed to createInitialState
const [state, dispatch] = useReducer(
reducer,
currentUserId, // This becomes the argument
createInitialState // This function receives currentUserId
);
Think of it like a chef receiving an ingredient order (initialArg) and preparing the final dish (initial state) before service begins.
Key Takeaway: The init function receives the second useReducer parameter as its argument and transforms it into the initial state—giving you control over how that transformation happens while keeping expensive logic lazy.