1. Why useReducer — When useState Gets Messy

useState is perfect for a single, independent piece of state: a toggle, a counter, a form field. But real applications have state that travels together. The UrbanCart shopping cart is a classic example — adding an item, removing it, and changing its quantity are all tightly coupled operations on the same list.

When you try to model this with multiple useState calls, you end up with scattered set* calls spread across many event handlers. A single "add to cart" action might need to update the items array, recalculate totals, and flag whether the cart is empty — three state updates that must be perfectly consistent.

🛒
UrbanCart Problem
Shopping cart state with useState

Imagine managing the UrbanCart cart with multiple useState hooks:

  • Every action (add, remove, update qty) requires co-ordinated updates to 3+ state variables
  • Logic is duplicated or spread across different components and handlers
  • If one update happens but another doesn't (e.g., totals don't recalculate), the cart state becomes inconsistent
  • Testing is difficult because the logic is interleaved with the UI

useReducer solves this by pulling all state logic into one place — a pure function that takes the current state and an action, and returns the next state. Every update goes through that one function, making state changes predictable, testable, and easy to reason about.

useState vs useReducer — When to Reach for Each
useState
1–2 independent values
→ too many? →
useReducer
Related state + complex logic

2. The Reducer Function — (state, action) => newState

A reducer is a pure function. It takes two arguments — the current state and an action object — and returns the next state. That's the entire contract. No side effects, no API calls, no randomness. Same inputs always produce the same output.

cartReducer.js Reducer function signature
✅

Pure function rules

No mutations. No state.items.push(). Always return a new object or array. This keeps React's change detection working correctly.

🔀

switch on action.type

Each case handles one action type. The default case returns the current state unchanged — critical for actions you don't handle.

Why "pure"? A pure function has no side effects and depends only on its inputs. This makes reducers trivially unit-testable: pass in a state and an action, assert on the output. No mocking, no setup.

A minimal counter reducer

Before tackling the full cart, here's the pattern with a simple counter — easier to see all the parts clearly:

counterReducer.js Simple counter reducer
Tracing state changes through the reducer
Initial: { count: 0, step: 1 } INCREMENT → { count: 1, step: 1 } INCREMENT → { count: 2, step: 1 } SET_STEP(5)→ { count: 2, step: 5 } INCREMENT → { count: 7, step: 5 } RESET → { count: 0, step: 1 }

3. dispatch — Sending Action Objects

useReducer gives you two things: the current state, and a dispatch function. You call dispatch with an action object to trigger a state update. React passes your action to the reducer, gets back the new state, and re-renders.

Counter.jsx useReducer hook + dispatch
Key insight: You never call the reducer directly. You call dispatch(action), and React calls the reducer for you. This is the same pattern Redux uses — dispatching an action describes what happened, and the reducer decides what the new state should be.
How useReducer Works
User Event
button click
→
dispatch(action)
{type, payload}
→
reducer(state, action)
returns new state
→
Re-render
with new state

4. Action Types — ADD_ITEM, REMOVE_ITEM, UPDATE_QUANTITY, CLEAR_CART

Action types are just strings that identify what happened. Convention is SCREAMING_SNAKE_CASE. For the UrbanCart shopping cart, we need four actions:

➕

ADD_ITEM

Adds a product to the cart. If it already exists, increments its quantity instead of duplicating.

➖

REMOVE_ITEM

Removes an item from the cart entirely, regardless of quantity. Takes the item's id as payload.

🔢

UPDATE_QUANTITY

Sets an item's quantity to a specific number. Useful for the quantity input on the cart page. Takes id and quantity.

🗑️

CLEAR_CART

Empties the entire cart. No payload needed — just reset items to an empty array.

cartReducer.js Full UrbanCart reducer
Notice: The total is derived inside the reducer on every update, not stored separately. This is the pattern — computed values live in the reducer, not spread across multiple state variables.

5. useReducer vs useState — When to Pick Which

There's no strict rule, but these guidelines work well in practice:

🪝

Use useState when...

  • You have 1–2 independent values
  • Updates are simple (toggle, increment, set string)
  • The next state doesn't depend on the previous state in a complex way
  • State values don't change together
⚙️

Use useReducer when...

  • Multiple state values are related and updated together
  • State logic is complex (conditionals, derived values)
  • The next state depends on the previous state and an action
  • You want testable, co-located state logic
comparison.jsx useState vs useReducer side-by-side
Practical rule: If you find yourself writing three or more related setState calls in a single event handler, that's a strong signal to reach for useReducer.

6. Combining useReducer with useContext — Mini Redux

On its own, useReducer keeps state local to one component. But UrbanCart's cart needs to be accessible from the product list, the navbar (item count), and the cart page. Combining useReducer with useContext gives you app-wide shared state — this is the lightweight "mini Redux" pattern used in many production apps.

CartContext.jsx useReducer + useContext pattern
Mini Redux Pattern
CartProvider
useReducer lives here
→
CartContext
state + dispatch
→
Any component
useCart() hook
This is how Redux works at its core. Redux adds middleware, dev tools, and a global store, but the fundamental data flow is identical: dispatch an action → reducer returns new state → UI re-renders. Learning this pattern with useReducer + useContext means you already understand Redux conceptually.

7. Try It Yourself — Counter Reducer

Let's start with the simple counter reducer to see the pattern clearly. This editor shows INCREMENT, DECREMENT, RESET, and SET_STEP actions. Edit the reducer or add a new action type to experiment.

Try It Yourself — Counter Reducer
Preview

8. Try It Yourself — UrbanCart Reducer

The full shopping cart with all four action types. A product catalogue on the left lets you add items; the cart panel on the right shows items, quantities, and total. You can add, remove, update quantity, and clear the cart.

Try It Yourself — UrbanCart useReducer
Preview

Quiz

Question 1 of 5
What does a reducer function take as arguments?
Question 2 of 5
How do you trigger a state update when using useReducer?
Question 3 of 5
What should a reducer function always return?
Question 4 of 5
When should you prefer useReducer over useState?
Question 5 of 5
What is the typical shape of an action object dispatched to a reducer?
0
/ 5
Great job!

You completed the useReducer quiz.

Next Lesson

Custom Hooks →
Extract and reuse stateful logic across components — no duplication, clean code.
Africa & India's Best AI Academy
🤖 AI-first 🎓 Placement Assistance

You just built a production-grade cart reducer.
Now build a career with the same momentum.

Join the Best AI Programs — three 5-month courses, fully online, with placement assistance. Week 1 is free.

Explore our AI-era courses →