Advanced HooksPro· 35 min read

useReducer

Manage complex state with clear, predictable update logic — the foundation of Redux-style state.

What you will learn

  • Use useReducer for structured state
  • Write a reducer function
  • Dispatch actions

State logic in one place

When state updates get complex, useReducer centralises the logic in a reducer — a function that takes the current state and an action, and returns the next state.

useReducer centralises update logic
function reducer(state, action) {
  switch (action.type) {
    case "inc": return { count: state.count + 1 };
    case "dec": return { count: state.count - 1 };
    case "reset": return { count: 0 };
    default: return state;
  }
}

function App() {
  const [state, dispatch] = useReducer(reducer, { count: 0 });
  return (
    <div>
      <h2>Count: {state.count}</h2>
      <button onClick={() => dispatch({ type: "inc" })}>+</button>
      <button onClick={() => dispatch({ type: "dec" })}>-</button>
      <button onClick={() => dispatch({ type: "reset" })}>Reset</button>
    </div>
  );
}
Live preview

Here is the cycle each time you click a button:

  1. A button dispatches an action — a small object describing what happened, e.g. dispatch({ type: "inc" }).
  2. React calls the reducer with the current state and that action.
  3. The reducer’s switch matches action.type and returns the next state"inc" returns count + 1, "dec" returns count - 1, "reset" returns 0, anything else returns the state unchanged.
  4. React re-renders with the new state, so the count on screen updates.

The win is that all the update rules live in one place (the reducer), instead of being scattered across many setState calls. That keeps complex state predictable.

Note: Output: Count: 0 with +, - and Reset buttons. + makes it 1, 2, 3…; - goes back down; Reset returns it to 0.

Note: You dispatch an action ({ type: "inc" }), and the reducer decides the next state. This pattern scales well and is the heart of Redux, a popular state library.

Q. In useReducer, what does dispatch do?

Answer: dispatch sends an action object to the reducer, which returns the next state based on the action type.

✍️ Practice

  1. Build a counter using useReducer with inc/dec/reset actions.
  2. Add a “set to 10” action.

🏠 Homework

  1. Build a simple to-do reducer with add and remove actions.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →