Q19: When should you use useReducer instead of useState?
useReducer is preferable for complex state logic involving multiple sub-values, nested state updates, or where the next state depends on the previous state across multiple user actions. It follows the Redux-like pattern (state, action) => newState.
useReducer State Machine
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case 'increment': return { count: state.count + 1 };
case 'decrement': return { count: state.count - 1 };
default: throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return <button onClick={() => dispatch({ type: 'increment' })}>{state.count}</button>;
}useReducer centralizes action updates inside pure functions, decoupling UI interactions from state mutation rules.
Key Takeaways
Centralizes complex state update logic into a pure reducer function.
Passes stable
dispatchfunction pointers down to optimize child renders.
Knowledge Check
Is the dispatch function reference returned from useReducer guaranteed to be stable across re-renders?