Stop 10 · State Management & Data FetchingTopics · 2/8

useReducer Hook

Part of the MERN Stack Roadmap

In short

When a component has many related pieces of state and many ways to change them, a pile of useState calls gets messy. useReducer puts all the update rules in one function you can read, test and trust.

useReducer manages complex state with a reducer function that takes the current state and an action and returns the new state, keeping all update logic in one place.

The jaadu sits behind a bank counter window, taking a paper slip from a customer and stamping a passbook with a big rubber stamp.

Think of it like this

The bank counter slip

At an SBI branch you don't walk into the vault and change your balance. You fill a slip saying "DEPOSIT ₹2,000" and hand it over. The cashier follows fixed rules and gives you the new balance. The slip is an action, the cashier is the reducer, and the passbook is the state.

Watch it happen

Actions flowing through a cart reducer

items: 0
0
total: ₹0
1

1/5The starting state: an empty cart.

The big ideas

What you need to know

reducer(state, action)

A pure function: same state and action always give the same new state. No fetch calls or random values inside.

dispatch an action

Components call dispatch({ type: "added", product }) to describe what happened, not how to change state.

Return new objects

Never mutate state. Return a new object using spread, so React notices the change.

useState or useReducer?

useState for one or two simple values. useReducer when updates depend on each other or there are many action types.

See it in code

Walk through the code

jsx
1import { useReducer } from "react";2 3const initialState = { items: [], total: 0 };4 5function cartReducer(state, action) {6  switch (action.type) {7    case "added": {8      const items = [...state.items, action.product];9      return { items, total: state.total + action.product.price };10    }11    case "removed": {12      const item = state.items.find((i) => i._id === action.id);13      if (!item) return state;14      return {15        items: state.items.filter((i) => i._id !== action.id),16        total: state.total - item.price,17      };18    }19    case "cleared":20      return initialState;21    default:22      throw new Error("Unknown action: " + action.type);23  }24}25 26export default function MiniCart({ product }) {27  const [cart, dispatch] = useReducer(cartReducer, initialState);28  return (29    <div>30      <p>{cart.items.length} items, ₹{cart.total}</p>31      <button onClick={() => dispatch({ type: "added", product })}>Add {product.name}</button>32      <button onClick={() => dispatch({ type: "cleared" })}>Clear</button>33    </div>34  );35}

1/5The reducer gets the current state and an action, and switches on action.type.

A small cart whose rules all live in one reducer.

Save yourself the pain

Common mistakes

Oops

Writing state.items.push(product); return state; in the reducer.

Do this instead

Return a new object with a new array. Mutating means React sees the same reference and may not re-render.

Oops

Calling fetch or saving to localStorage inside the reducer.

Do this instead

Keep reducers pure. Do side effects in event handlers or useEffect, then dispatch the result.

Oops

Forgetting a default case, so a typo silently returns undefined.

Do this instead

Add a default that throws or returns state, so mistakes are obvious.

Your mission

A signup form reducer

~30 min

Quick check

What should a reducer do with an action it does not recognise?

Go deeper

  1. 1Rewrite a cart's add, remove and change quantity logic as a reducer.
  2. 2Use clear action types like 'cart/added' and keep reducers pure.
  3. 3Combine useReducer with context for a small app-wide store.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge