When state gets complex — several values that change together, or the next state depends on the action taken — a pile of useState calls becomes hard to follow. useReducer centralises all the update logic in one predictable function, the same pattern that powers Redux.
Why useReducer?
It shines when updates are related and rule-based (a form with validation, a multi-step wizard, a shopping cart). All the "how state changes" logic lives in one place instead of scattered across handlers, which makes it testable and easy to reason about.
The reducer function
A reducer is a pure function (state, action) => newState. It never mutates — it returns a new state based on the action's type:
function reducer(state, action) {switch (action.type) {case "increment": return { ...state, count: state.count + 1 };case "reset": return { count: 0 };case "setName": return { ...state, name: action.payload };default: return state;}}
Dispatching actions
import { useReducer } from "react";function Counter() {const [state, dispatch] = useReducer(reducer, { count: 0, name: "" });return (<><p>{state.count}</p><button onClick={() => dispatch({ type: "increment" })}>+</button><button onClick={() => dispatch({ type: "reset" })}>Reset</button></>);}
You call dispatch with an action object; React runs the reducer and re-renders with the new state. Components stay simple — they just describe what happened, not how state changes.
useReducer vs useState
| Use… | When |
|---|---|
useState | Simple, independent values (a toggle, a text field) |
useReducer | Complex state, many related updates, or next-depends-on-action logic |
Practice
Rebuild a shopping-cart state with useReducer: actions for add, remove, updateQty and clear. Keep the reducer pure (spread, no mutation) and have the component only dispatch actions.
Key takeaways
- 01useReducer centralises complex update logic in one pure (state, action) => newState function.
- 02A reducer switches on action.type and returns new state immutably — never mutates.
- 03dispatch(action) triggers the reducer and a re-render; components just say what happened.
- 04Use useState for simple independent values; useReducer for complex, related state.
- 05It's the same mental model as Redux, built into React.
