Comparing useState Lazy Init vs useReducer
What you'll learn: How useState(() => value) and useReducer's init function solve the same problem with different syntax and use cases.
Both useState and useReducer support lazy initialization to avoid expensive computations on every render. They tackle the same performance problem but with different approaches.
useState Lazy Initialization
You pass a function to useState instead of a direct value:
const [state, setState] = useState(() => {
return expensiveComputation();
});
This function runs only once during the initial render. On subsequent re-renders, React ignores it completely.
useReducer Lazy Initialization
You provide an init function as the third parameter:
const [state, dispatch] = useReducer(
reducer,
initialArg,
(arg) => {
return expensiveComputationUsing(arg);
}
);
The init function receives initialArg and transforms it into the initial state. Like useState's lazy function, it runs only once.
When to Choose Which
Use useState lazy init when:
- You have simple state that just needs an expensive starting value
- The initialization logic is straightforward
- You don't need the initializer to accept arguments
Use useReducer with init when:
- You're already using
useReducerfor complex state logic - You want to pass configuration arguments to the initializer
- You need to share or reuse the initialization logic (the
initfunction can be extracted and tested)
Think of it like calculating a recipe's ingredients: useState says "here's a function to figure out the ingredients once," while useReducer says "here's how to calculate ingredients based on the number of guests."
Key Takeaway: Both useState(() => value) and useReducer's init function prevent expensive initial computations from running on every render, but useReducer offers more flexibility by accepting arguments and separating initialization logic from the reducer itself.