useReducer
useReducer moves all of a component's update logic into one pure function, the reducer, that takes the current state and an action and returns the next state. It keeps related values in sync and, combined with Context, gives you a lightweight store.
36.1 The problem: two separate useStates
- Cart keeps items and total in two separate states.
- add() updates both (a pen and ₹20), but clear() only empties items and forgets the total.
- Add two pens, click Clear: the screen shows 0 items, ₹40.
function Cart() { const [items, setItems] = useState([]); const [total, setTotal] = useState(0); const add = () => { setItems([...items, "Pen"]); setTotal(total + 20); }; const clear = () => setItems([]); return <div> <button onClick={add}>Add pen</button> <button onClick={clear}>Clear</button> <p>{items.length} items, ₹{total}</p> </div>;}0 items, ₹0-- Add pen x2 --2 items, ₹40-- Clear --0 items, ₹4036.2 Why is useReducer used?
- items and total are related parts of the same cart, but their update logic is scattered across every event handler.
- Today two handlers; tomorrow remove, quantity and coupon too, and keeping both states in sync everywhere is your job.
- We need all update logic in one place where each change is written once: a reducer.
36.3 The reducer
- A normal JavaScript function: (state, action) => next state.
- An action is a plain object whose type says what happened, e.g. "added".
- "added" returns a new object with items and total updated together; "cleared" resets both together, so the bug is impossible.
- The default branch throws for an unknown action, so a typo in the type is caught immediately.
export function cartReducer(state, action) { switch (action.type) { case "added": return { items: [...state.items, action.name], total: state.total + action.price, }; case "cleared": return { items: [], total: 0 }; default: throw Error("Unknown: " + action.type); }}36.4 Fix: useReducer
- useReducer(cartReducer, { items: [], total: 0 }) takes the reducer and the initial state.
- It returns a pair like useState: cart (current state) and dispatch (sends actions).
- The handlers no longer calculate anything; they only say what happened.
- Clicking Add pen twice then Clear now gives 0 items, ₹0.
import { useReducer } from "react";import { cartReducer } from "./cartReducer"; function Cart() { const [cart, dispatch] = useReducer( cartReducer, { items: [], total: 0 }); const add = () => dispatch( { type: "added", name: "Pen", price: 20 }); const clear = () => dispatch({ type: "cleared" }); return <div> <button onClick={add}>Add pen</button> <button onClick={clear}>Clear</button> <p>{cart.items.length} items, ₹{cart.total}</p> </div>;}0 items, ₹0-- Add pen --1 items, ₹20-- Add pen --2 items, ₹40-- Clear --0 items, ₹036.5 How it works: the dispatch flow
- Step 1
1.Click Add pen: handler calls dispatch({ type: "added", name: "Pen", price: 20 })
- Step 2
2.React calls cartReducer(currentState, action)
- Step 3
3.Reducer returns a NEW state object
- Step 4
4.React compares by reference, sees a change
- Step 5
5.Component re-renders: 1 items, ₹20
dispatch does not change state itself; it sends a request to React
36.6 Checkpoint: reducers are pure
- Calling cartReducer directly (no React) with start, then with its result: two.total is 40 but start.total is still 0.
- The reducer never modifies the start object; it returns a new object every time.
- Bonus: you can test a reducer without any browser.
import { cartReducer } from "./cartReducer.js"; const start = { items: [], total: 0 };const addPen = { type: "added", name: "Pen", price: 20,};const one = cartReducer(start, addPen);const two = cartReducer(one, addPen); console.log(two.total);console.log(start.total);> 40> 036.7 Common mistakes
- Mutating state: push into existing items, change total in place, return the same object.
- React compares old and new state by reference; the same object means "nothing changed", so the screen does not update.
- Fix: always return a new object and a new array.
// Wrong: mutates and returns the same object -> screen does not updatecase "added": state.items.push(action.name); state.total = state.total + action.price; return state;// Right: new object + new array -> re-rendercase "added": return { items: [...state.items, action.name], total: state.total + action.price, };- Myth: "useReducer is a global store like Redux". It is local state like useState; every component that calls it gets its own copy.
- Myth: "useReducer is faster". It only organises update logic; to make it global, combine it with Context.
36.8 Comparison: useState vs useReducer
| Point | useState | useReducer |
|---|---|---|
| Best for | Simple, independent values | Related values that change together |
| Examples | Input text, modal open | Cart (items + total), multi-step forms |
| Where logic lives | In each event handler | One pure reducer function |
| Next state depends on previous? | Fine for simple cases | Natural fit |
| Testing | Through the component | Call the reducer directly |
- Simple test: if the same setState calls keep repeating in your handlers, move that logic into a reducer.
36.9 Reducer + Context = store
- Create CartContext; inside CartProvider get cart and dispatch from useReducer and pass both as the context value.
- Wrap the app in CartProvider; any deep component gets dispatch with useContext and sends actions without prop drilling.
- The header cart count and any Add button all update through one reducer.
import { createContext, useReducer } from "react";import { cartReducer } from "./cartReducer"; export const CartContext = createContext(null); export function CartProvider({ children }) { const [cart, dispatch] = useReducer( cartReducer, { items: [], total: 0 }); return ( <CartContext value={{ cart, dispatch }}> {children} </CartContext> );}- Step 1
1.CartProvider: useReducer(cartReducer, initial)
- Step 2
2.Provides { cart, dispatch } via CartContext
- Step 3
3.Deep AddButton: useContext(CartContext).dispatch(action)
- Step 4
4.Reducer returns new cart state
- Step 5
5.Header and every consumer re-render with the new cart
36.10 Rules for reducers
- Pure: no side effects like fetch, timers or random values inside a reducer.
- Never mutate state; always return a new object.
- The action type says what happened (added, cleared).
- Throw for an unknown action so a typo is caught immediately.
36.11 Interview tips
- useReducer is a hook for complex state that returns the state and a dispatch function.
- All update logic lives in one pure reducer: (state, action) => next state.
- Choose it for related values and many actions; useState for simple independent values.
- Together with Context it makes a lightweight global store; by itself it is local state.