When state updates get tangled — multiple related fields, transitions that depend on the previous state, or the same update logic scattered across handlers — useReducer centralizes everything into a single reducer function.
Shape
const [state, dispatch] = useReducer(reducer, initialState);
function reducer(state, action) {
switch (action.type) {
case 'SET_X': return { ...state, x: action.payload };
default: return state;
}
}
dispatch({ type: 'SET_X', payload: 42 });
A reducer is a pure function: given the same state + action, it always returns the same next state. No side effects, no mutation.
Your Task
Rebuild the counter from chapter 3 with useReducer:
- Initial state:
{ count: 0 }
- Handle action types:
'INCREMENT', 'DECREMENT', 'RESET'
- Display count in
<h2 id="count">
- Buttons
#increment, #decrement, #reset dispatch the matching action