Skip to main content
Albero Academy

useReducer & Complex State

Manage complex, related state with a reducer — actions, the dispatch pattern, and when it beats multiple useState calls.

Chapter 7React15 min readBeginner friendly
  • #React
  • #useReducer
  • #State

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:

a reducer
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

useReducer in a component
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
useStateSimple, independent values (a toggle, a text field)
useReducerComplex 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

  1. 01useReducer centralises complex update logic in one pure (state, action) => newState function.
  2. 02A reducer switches on action.type and returns new state immutably — never mutates.
  3. 03dispatch(action) triggers the reducer and a re-render; components just say what happened.
  4. 04Use useState for simple independent values; useReducer for complex, related state.
  5. 05It's the same mental model as Redux, built into React.