The init Function Parameter
What you'll learn: How to delay expensive initial state calculations in useReducer until the component actually mounts, improving performance.
The Problem Recap
In the previous lesson, you learned that passing a complex computation directly as useReducer's initial state runs that computation on every render, even though the result is only used once. This wastes resources.
The Solution: Lazy Initialization
useReducer accepts an optional third parameter: an init function. When provided, React calls this function with the second parameter as its argument, and uses the return value as the initial state.
const init = (initialArg) => {
// Expensive computation runs ONLY on mount
return computeExpensiveInitialState(initialArg);
};
const [state, dispatch] = useReducer(reducer, someValue, init);
The key difference: the init function runs only once when the component mounts, not on every re-render.
How It Works
- You pass three arguments to
useReducer:(reducer, initialArg, init) - On mount, React calls
init(initialArg)to get the initial state - On subsequent renders, React ignores the
initfunction entirely
When to Use It
Use the third parameter when your initial state requires:
- Parsing large data structures
- Reading from localStorage
- Complex calculations based on props
- Any operation you want to run once, not repeatedly
Key Takeaway: The init function parameter in useReducer lets you compute initial state lazily—running expensive setup logic only on mount, avoiding unnecessary work on every re-render.