Thuta Learning
React
IntermediateWeb DevelopmentIntermediate

State Architecture with useReducer

ReactLesson 1435 min

What you'll walk away with

  • Explain how useReducer(reducer, initialState) returns [state, dispatch] and how an action object describes what happened
  • Write a pure reducer that returns new objects and arrays instead of mutating state
  • Test a reducer as a plain function without React
  • Choose between useState and useReducer, and pass state and dispatch through two contexts

Explain it simply

Explain it simply

In a restaurant, waiters do not walk into the kitchen and cook. They hand in an order slip: "table 5 ordered one fried rice". The chef alone knows the rules for cooking and does the work.

useReducer works the same way. Event handlers are the waiters: they only send an action, the order slip, with dispatch({ type: 'added', text }). The reducer function is the chef: it looks at the current state and the action and returns the next state. Every rule about how state changes now lives in one place.

Problem → Why → Solution

The problem: scattered updates, and a toggle that never shows

In a task app, each handler calls setTasks in its own way, and every new feature adds another handler with its own update logic. handleToggle edits the task object directly and passes the same old array back to setTasks, so clicking the checkbox changes nothing on screen, until some unrelated render suddenly reveals it.

TaskApp.jsx
function TaskApp() {
  const [tasks, setTasks] = useState([]);
  const [nextId, setNextId] = useState(1);

  function handleAdd(text) {
    setTasks([...tasks, { id: nextId, text, done: false }]);
    setNextId(nextId + 1);
  }
  function handleToggle(id) {
    const task = tasks.find((t) => t.id === id);
    task.done = !task.done;   // mutates the existing object
    setTasks(tasks);          // same array: React skips the re-render
  }
  function handleClearDone() {
    setTasks(tasks.filter((t) => !t.done));
  }
  // ...every new feature adds another handler with its own update logic
}

Why does this happen?

React compares the new state with the old one using Object.is. Passing back the same array looks like "nothing changed", so React skips the re-render. With logic scattered over many handlers, mutations like this are hard to spot. Gathering it in a reducer puts every update rule in one place you can read and test.

Core concept: handlers say what happened, the reducer decides how state changes

const [state, dispatch] = useReducer(reducer, initialState); gives you the current state, just like useState, but a dispatch function instead of a setter. Handlers send an action object such as dispatch({ type: 'added', id, text }). Name an action's type after what the user did (added, toggled, cleared_done), not as an instruction for how to change state, like set_tasks. React calls reducer(currentState, action) and uses its return value as the state for the next render.

A reducer must be pure. The same inputs give the same output, and it never modifies state: build new arrays with [...items, newItem], map() and filter(), and new objects with { ...item, done: true }. Keep side effects and unstable values such as fetch, setTimeout, Math.random() and Date.now() out of reducers; create values like ids in the handler and put them in the action. In development, Strict Mode calls your reducer twice to expose impurity. Throwing on unknown action types in the default case reveals typos immediately.

After dispatch, the state variable does not change right away: inside the current handler, state is still this render's snapshot, and the new value appears on the next render. If the reducer returns the exact same state, React can skip the re-render. The dispatch function keeps the same identity across renders, so it is safe to pass down to children.

A reducer is a plain JavaScript function that does not even import React. You can unit-test it without a browser: give it a state and some actions, then check the result.

Mental model: order slip to the chef
  1. A handler dispatches an action
  2. React calls reducer(state, action)
  3. The reducer returns new state
  4. The next render sees the new state

Handlers describe what happened; the reducer decides how state changes.

General pattern

jsx
function reducer(state, action) {
  switch (action.type) {
    case 'something_happened':
      return { ...state, field: action.payload };   // new object, no mutation
    default:
      throw new Error('Unknown action: ' + action.type);
  }
}

const [state, dispatch] = useReducer(reducer, initialState);
dispatch({ type: 'something_happened', payload: value });

The reducer returns new state based on action.type. In the component, useReducer provides state and dispatch, and handlers send actions through dispatch.

Example: a counter driven by a reducer

The counter's two update rules, increment and reset, live in a reducer outside the component. The buttons never touch state directly; they only dispatch actions. useState would be enough for a counter this small; it was chosen so the pattern itself is easy to see.

jsx
import { useReducer } from 'react';

function reducer(state, action) {
  switch (action.type) {
    case 'increment': return { count: state.count + 1 };
    case 'reset': return { count: 0 };
    default: throw Error('Unknown action: ' + action.type);
  }
}

export default function Counter() {
  const [state, dispatch] = useReducer(reducer, { count: 0 });
  return <>
    <p>Count: {state.count}</p>
    <button onClick={() => dispatch({ type: 'increment' })}>Add</button>
    <button onClick={() => dispatch({ type: 'reset' })}>Reset</button>
  </>;
}

Code breakdown

  1. Line 3function reducer(state, action) {

    Declared outside the component, it depends only on state and action, never on props or component variables, which makes it easy to test.

  2. Line 5case 'increment': return { count: state.count + 1 };

    Instead of state.count++, it returns a brand-new object, which React sees as a change and re-renders.

  3. Line 7default: throw Error('Unknown action: ' + action.type);

    A typo such as dispatch({ type: 'incremnt' }) fails loudly instead of silently leaving state unchanged.

  4. Line 12const [state, dispatch] = useReducer(reducer, { count: 0 });

    Pass the reducer and the initial state; get back the current state and dispatch.

  5. Line 15<button onClick={() => dispatch({ type: 'increment' })}>Add</button>

    The button only reports that an increment happened; it does not know how count is computed.

You should see
Count: 0 renders with Add and Reset buttons. Each Add click raises the count by one (Count: 1, Count: 2 ...), and Reset brings it back to Count: 0.

Choosing between useState and useReducer

SituationuseStateuseReducer
Shape of stateOne boolean, string or numberSeveral related fields
Update pathsOne or twoMany events update the same state
DebuggingHunt for every setState callLog each action in the reducer
TestingThrough the componentUnit-test the reducer alone

As an app grows, reducers pair naturally with context. Splitting state and dispatch into two contexts lets any component in the tree dispatch actions without prop drilling. Because dispatch never changes, components that read only the dispatch context are not re-rendered through it when the state changes.

TasksContext.jsx
import { createContext, useContext, useReducer } from 'react';
import { tasksReducer } from './tasksReducer.js';

const TasksContext = createContext(null);
const TasksDispatchContext = createContext(null);

export function TasksProvider({ children }) {
  const [tasks, dispatch] = useReducer(tasksReducer, []);
  return (
    <TasksContext value={tasks}>
      <TasksDispatchContext value={dispatch}>{children}</TasksDispatchContext>
    </TasksContext>
  );
}

export const useTasks = () => useContext(TasksContext);
export const useTasksDispatch = () => useContext(TasksDispatchContext);

In real projects

Where this shows up in real projects

Reducers show up in features with many ways to change state: shopping carts, multi-step checkout wizards, drag-and-drop boards, editors with undo and redo. Because the action log shows, in order, what the user did, you can replay an action sequence from a bug report to reproduce the problem. Redux, today usually through Redux Toolkit, scales this reducer-and-action pattern into one store for the whole app; useReducer is the small version for a single component or feature.

Teams keep reducers in their own files, such as tasksReducer.js, and test each action with Vitest or Jest. TypeScript projects declare actions as a discriminated union so the compiler warns about a missing case. When immutable updates of nested state get long, you will also see the Immer library used to write them more simply.

Common mistakes

Common mistakes

1. Mutating state inside the reducer

case 'added': state.push(action.task); return state; hands back the same array, so React may not see a change and can skip the re-render. Return a new array: return [...state, action.task];.

2. Doing side effects in the reducer

Calling fetch, writing to localStorage, or creating ids with crypto.randomUUID() inside a reducer happens twice under Strict Mode and gives inconsistent results. Move side effects to handlers or effects, and pass ids in through the action.

3. Reading the new state right after dispatch

dispatch({ type: 'added', task }); console.log(state.length); prints the length from before the task was added. If you need the result immediately, compute reducer(state, action) yourself, or use the state of the next render.

Best practices

Best practices

  • Make each action match one user action: a form submit that changes five fields is one submitted action, not five set_field actions.
  • Keep the reducer and its action types in their own file, outside the component, and write one test per action.
  • In development, a temporary console.log(action) at the top of the reducer shows, in order, how state evolves.
  • Do not force all state into the reducer; unrelated local state, such as whether an input is focused, is better served by useState.

Mini challenge

Mini challenge: a shopping cart reducer

Write a pure reducer that manages cart items and a helper that computes the total, then wire them into a CartPage with useReducer. The reducer must be testable without React.

  • Four actions: added (product), quantity_changed (id, qty; 0 removes the item), removed (id) and cleared
  • added increases qty by 1 for a product already in the cart, otherwise adds it with qty: 1
  • Never mutate state, and throw on an unknown action
  • cartTotal(items) returns the sum of price × qty; CartPage shows the total and an empty message
Cart.jsx
import { useReducer } from 'react';

export function cartReducer(items, action) {
  switch (action.type) {
    // TODO: 'added'            -> +1 qty if present, else append with qty 1
    // TODO: 'quantity_changed' -> set qty; remove the item when qty <= 0
    // TODO: 'removed'          -> drop the item with action.id
    // TODO: 'cleared'          -> empty cart
    default:
      // TODO: throw for unknown actions
  }
}

export function cartTotal(items) {
  // TODO: sum of price * qty
}

export default function CartPage() {
  // TODO: useReducer with one Green tea (price 4, qty 2) to start
  // TODO: list items with "-" and "Remove" buttons, an "Add cake" button,
  //       a "Clear" button, "Total: N USD", and an empty-cart message
}

Expected: At first: Green tea x 2, Total: 8 USD After Add cake: Cake x 1 appears and Total: 14 USD Clicking - on Green tea twice removes it: Total: 6 USD After Clear: Your cart is empty. and Total: 0 USD Called directly, the reducer throws "Unknown action: refunded" for { type: 'refunded' }.

Show hint

Wrap the added case in { } so you can declare a const inside it. Change a quantity with items.map(item => item.id === id ? { ...item, qty } : item). Try the reducer in Node with a sequence of actions and console.log the result.

Show solution
Cart.jsx
import { useReducer } from 'react';

export function cartReducer(items, action) {
  switch (action.type) {
    case 'added': {
      const exists = items.some((item) => item.id === action.product.id);
      if (!exists) return [...items, { ...action.product, qty: 1 }];
      return items.map((item) =>
        item.id === action.product.id ? { ...item, qty: item.qty + 1 } : item,
      );
    }
    case 'quantity_changed':
      if (action.qty <= 0) return items.filter((item) => item.id !== action.id);
      return items.map((item) =>
        item.id === action.id ? { ...item, qty: action.qty } : item,
      );
    case 'removed':
      return items.filter((item) => item.id !== action.id);
    case 'cleared':
      return [];
    default:
      throw new Error('Unknown action: ' + action.type);
  }
}

export function cartTotal(items) {
  return items.reduce((sum, item) => sum + item.price * item.qty, 0);
}

const CAKE = { id: 'cake', name: 'Cake', price: 6 };
const START = [{ id: 'tea', name: 'Green tea', price: 4, qty: 2 }];

export default function CartPage() {
  const [items, dispatch] = useReducer(cartReducer, START);

  return (
    <section>
      {items.length === 0 && <p>Your cart is empty.</p>}
      <ul>
        {items.map((item) => (
          <li key={item.id}>
            {item.name} x {item.qty}{' '}
            <button type="button" onClick={() =>
              dispatch({ type: 'quantity_changed', id: item.id, qty: item.qty - 1 })}>
              -
            </button>
            <button type="button"
              onClick={() => dispatch({ type: 'removed', id: item.id })}>
              Remove
            </button>
          </li>
        ))}
      </ul>
      <button type="button" onClick={() => dispatch({ type: 'added', product: CAKE })}>
        Add cake
      </button>
      <button type="button" onClick={() => dispatch({ type: 'cleared' })}>Clear</button>
      <p>Total: {cartTotal(items)} USD</p>
    </section>
  );
}

Quick quiz 1 / 3

Which reducer case is correct for a 'toggled' action?

Quick quiz 2 / 3

With state.count at 0, a handler runs dispatch({ type: 'increment' }); console.log(state.count);. What is logged?

Quick quiz 3 / 3

When is useReducer a better fit than useState?

What to remember

  • useReducer(reducer, initialState) returns [state, dispatch], and handlers dispatch actions that describe what happened.
  • Reducers must be pure: return new objects and arrays, avoid side effects, and throw on unknown actions.
  • dispatch does not change the state variable you already have; the new value arrives on the next render.
  • Test reducers as plain functions, and as the app grows, pass state and dispatch through two contexts.

Extracting State Logic into a Reducer — React

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.