ReactMedium
What is useReducer?
useReducer(reducer, initialState) manages state with a reducer function (state, action) => newState. It returns [state, dispatch]; you call dispatch({ type: "added", item }) and React computes the next state with your reducer. It is useful when state has several fields or when many different events update it.
Parts
- State: any value, usually an object.
- Actions: objects describing what happened (
{ type: "item_removed", id }). - Reducer: a pure function that returns the next state for each action. No side effects, no mutation (return new objects).
- Dispatch: stable across renders, safe to pass down or omit from dependency arrays.
- Lazy init:
useReducer(reducer, arg, init)computes the initial state once.
Benefits
- All update logic in one place, easy to read and unit test without rendering.
- Event handlers just describe what happened.
- Prevents impossible state combinations when modeling a state machine (
status: "idle" | "loading" | "success" | "error"). - Pairs with context to share state and
dispatchacross a subtree (a lightweight Redux).
Tips
- Name actions after events ("submitted", "item_added"), not setters.
- TypeScript discriminated unions make actions type-safe.
- Immer's
useImmerReducerlets you write mutating-style reducers. - Throw or warn on unknown action types.
Code example
tsx
1import { useReducer } from "react";23type Item = { id: string; name: string; qty: number };4type State = { items: Item[]; coupon?: string };5type Action =6 | { type: "added"; item: Item }7 | { type: "removed"; id: string }8 | { type: "qty_changed"; id: string; qty: number }9 | { type: "coupon_applied"; code: string };1011function cartReducer(state: State, action: Action): State {12 switch (action.type) {13 case "added":14 return { ...state, items: [...state.items, action.item] };15 case "removed":16 return { ...state, items: state.items.filter((i) => i.id !== action.id) };17 case "qty_changed":18 return { ...state, items: state.items.map((i) => (i.id === action.id ? { ...i, qty: action.qty } : i)) };19 case "coupon_applied":20 return { ...state, coupon: action.code };21 }22}2324export function Cart() {25 const [state, dispatch] = useReducer(cartReducer, { items: [] });26 return (27 <div>28 <button onClick={() => dispatch({ type: "added", item: { id: crypto.randomUUID(), name: "Pen", qty: 1 } })}>Add pen</button>29 {state.items.map((i) => (30 <p key={i.id}>31 {i.name} <input type="number" value={i.qty} onChange={(e) => dispatch({ type: "qty_changed", id: i.id, qty: +e.target.value })} />32 <button onClick={() => dispatch({ type: "removed", id: i.id })}>×</button>33 </p>34 ))}35 </div>36 );37}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.