Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Routing and Application Architecture
Stage 5: Specialization (pick ONE)

Part 10 / Stage 2

useReducer

Goal: Recognize the moment several related useState calls stop being a convenience and start being a liability; model a UI's state transitions as action objects and one pure reducer function; wire that reducer in with useReducer's signature, including its lazy-initialization third argument; know why dispatch's identity is guaranteed stable across renders; preview pairing a reducer with context; and test a reducer the cheapest way there is - as a plain function, no component involved. Time: ~5 hours ยท Level: comfortable with useState, immutable updates (Part 3), and useContext (Part 9)

What you will learn

  • The felt problem a reducer responds to: several useState calls that are all supposed to describe one idea (one cart, one form, one wizard step) can drift out of sync the moment an update to one of them is written without the others, with no syntax error anywhere to catch it
  • Action objects: a plain { type: "...", ...payload } value that names what happened, not what the new state should be - the reducer is the only place that decides the second part
  • A pure reducer function - (state, action) => newState - that never mutates state or anything inside it, always returns a brand-new value built with spread/map/filter, and produces the same output for the same inputs every time
  • useReducer's full signature: useReducer(reducer, initialArg, init?) - the [state, dispatch] pair it returns, and the optional third argument that computes the real initial state lazily, exactly once
  • dispatch's identity never changes across a component's re-renders - a real, provable guarantee a plain inline handler does not get
  • A preview of pairing useReducer with useContext (taught in full in Part 9) - one reducer behind one Provider, read through one custom hook, shared by siblings with no prop drilling
  • Testing a reducer in isolation: calling cartReducer(state, action) directly in a test file that never imports React or renders anything
  • This part's running example throughout: a Swiggy-style food-delivery cart, extended section by section from "three useState calls that can drift" to "one reducer, shared through context, tested without a component in sight"

A note on how this part is organised: same convention as Parts 1-9 - every examples/ and solutions/ file here is wired into this repo's own harness/ and actually executed before being shown below. When you build along, type the code into your own project; this repo's copy is the verified reference, not something you need to open.

Topics in this part

Practice

Every exercise below is a React component (or a reducer plus a component, or a Broken/Fixed pair) in its own .jsx file, paired with a .test.jsx that actually exercises it - rendering with Testing Library/userEvent where a component is involved, or calling a reducer directly as a plain function where it isn't. That is the same verified-output rule as every example in this course.


Exercise 1: A first reducer - an IRCTC-style seat quantity stepper

Scenario: A train-ticket booking screen lets a passenger pick how many seats to book (1 to 6), with "+", "-", and "Reset to 1" controls. What to do: Write a pure seatQuantityReducer(state, action) where state is { quantity: number } and the three action types are "increment", "decrement", and "reset". "increment" must never go above 6; "decrement" must never go below 1; "reset" always returns { quantity: 1 }. Then write SeatQuantityStepper(), a component that wires it in with useReducer and renders the three buttons plus the current quantity.

Sample output (really run):

initial                  -> Quantity: 1
click "+" five times     -> Quantity: 6
click "+" again          -> Quantity: 6 (capped, no change)
click "-" twice          -> Quantity: 4
click "Reset to 1"       -> Quantity: 1

๐Ÿ’ก Hint: this is examples/03_usereducer_wiring.jsx's shape exactly - one reducer with a switch, one component that only dispatches. Test the reducer directly first (examples/02_cart_reducer_pure.test.jsx's style), then test the wired-up component separately.


Exercise 2: A passenger list reducer - add and remove, no duplicates

Scenario: The same booking screen needs a passenger list - a name typed into a text box, added to the booking with an "Add passenger" button, removable individually. What to do: Write a pure passengerReducer(state, action) where state is { passengers: string[] }, with action types "add" (payload: name) and "remove" (payload: index). "add" must reject (return state unchanged) a blank name (after trimming) or a name already in the list (case-insensitive). Then write PassengerList(), a controlled-input component (Part 5) wired to the reducer.

Sample output (really run):

type "Asha", click "Add passenger"   -> list: ["Asha"]
type "asha", click "Add passenger"   -> list: ["Asha"] (duplicate, case-insensitive, rejected)
type "  ", click "Add passenger"     -> list: ["Asha"] (blank, rejected)
type "Rohan", click "Add passenger"  -> list: ["Asha", "Rohan"]
click "Remove" next to "Asha"        -> list: ["Rohan"]

๐Ÿ’ก Hint: the "reject and return state unchanged" branch is still a valid reducer return - immutability doesn't mean every action has to produce a visibly different object, just that the reducer never mutates what it was given.


Exercise 3: Find and fix a mutation bug in a reducer

Scenario: A Zomato-style order-items reducer is supposed to let a kitchen screen mark one item "ready" without touching the others. A teammate wrote:

export function orderItemsReducerBroken(state, action) {
  if (action.type === "markReady") {
    const item = state.items.find((i) => i.id === action.id);
    item.status = "ready"; // mutates the object in place
    return state; // same reference - React sees "no change"
  }
  return state;
}

Testers report that marking an item ready sometimes updates the screen and sometimes doesn't, depending on what else happens to cause a rerender around the same time. What to do: Write both orderItemsReducerBroken (the code above, unchanged) and orderItemsReducerFixed, which returns a new items array (via .map()) and a new item object (via spread) instead of mutating either. Prove the difference the same way examples/02_cart_reducer_pure.test.jsx proves immutability: call each reducer, then check whether the original state object you passed in was changed by the call.

Sample output (really run - starting state has one item, { id: "o1", status: "pending" }):

orderItemsReducerBroken: originalState.items[0].status is now "ready" too - the old state object was mutated
orderItemsReducerFixed:  originalState.items[0].status is still "pending" - a new object was returned instead

๐Ÿ’ก Hint: this part's Section 3/Common mistakes names the exact symptom - a reducer that mutates and returns the same reference can make React treat a real change as "nothing changed," and whether that shows up depends on what else happens to trigger a render around the same time, which is why it is intermittent rather than consistently broken.


Exercise 4: Prove a lazy initializer really only runs once

Scenario: A "recently viewed products" widget restores its list from localStorage on mount, using useReducer's third argument - exactly examples/04_lazy_init.jsx's pattern, applied to a new domain. What to do: Write loadRecentlyViewed(storageKey) (parses JSON from localStorage, falling back to { productIds: [] }, and increments a module-level call counter the same way examples/04_lazy_init.jsx's loadCallCounts does) and RecentlyViewedWidget({ storageKey }), wired with useReducer(recentlyViewedReducer, storageKey, loadRecentlyViewed). Give the reducer one action type, "view" (payload: productId), that prepends a product id if it isn't already first, capped at 5 ids.

Sample output (really run - pre-seed localStorage with 2 ids, then click "View P100" three times):

after mount:        productIds: ["P1", "P2"]   (restored, call count: 1)
after 3 clicks:      productIds: ["P100", "P1", "P2"]  (no duplicate, still only 3 entries)
load call count:     1   (unchanged by any of the three clicks)

๐Ÿ’ก Hint: the call counter is the actual proof - without it, "restoring once" and "restoring on every render but you can't tell because the result looks the same" are indistinguishable from the rendered output alone.


Exercise 5: Prove dispatch survives into a memoized child unchanged

Scenario: A delivery-tracking dashboard passes a dispatch function down into a React.memo-wrapped child button, on the assumption that dispatch's stable identity means the child never re-renders just because its parent did. What to do: Write orderReducer (any two action types is enough - e.g. "refresh" and "cancel"), a React.memo-wrapped RefreshButton({ dispatch }) that logs (into an array passed as a prop, or a module-level counter) every time it renders, and a parent OrderDashboard() that holds unrelated state (e.g. a clock tick from useState) causing it to re-render periodically. Prove RefreshButton does not re-render on the parent's unrelated re-renders, because dispatch passed to it never changes identity - then add a second, deliberately-broken child that receives a plain inline arrow function instead of dispatch, and show that one does re-render every time.

Sample output (really run, parent forced to rerender 3 times via an unrelated state update):

RefreshButton (passed dispatch):            render count stays at 1
BrokenButton (passed a fresh inline arrow):  render count climbs to 4

๐Ÿ’ก Hint: examples/05_dispatch_stability.jsx already proves dispatch's === stability directly - this exercise asks you to prove the consequence of that stability through React.memo, which only skips a re-render when every prop is === to its previous value (Part 12 covers React.memo itself in full; this exercise only needs the default "skip if all props are ===" behavior, no useCallback required for dispatch since it's already stable).


Exercise 6: Build a small reducer + context store for a wishlist

Scenario: A wishlist needs to be shared between a product grid (where items get added) and a header badge (that shows the count) and a wishlist page (that lists and removes them) - three unrelated parts of the tree, exactly the shape examples/06_reducer_context_preview.jsx previews for a cart. What to do: Build WishlistStoreProvider, useWishlistStore (with the safety-throw-outside-provider idiom), and a wishlistReducer with "add", "remove", and "clear" action types - deduplicating by product id on "add", the same way Exercise 2's passenger list deduplicates by name. Then build three consuming components (WishlistAddControl, WishlistBadge, WishlistPage) that each call useWishlistStore() for only what they need.

Sample output (really run, all three rendered together inside one WishlistStoreProvider):

initial:                       WishlistBadge: "Wishlist: 0"
add "Running Shoes" twice:     WishlistBadge: "Wishlist: 1"  (deduplicated)
add "Yoga Mat":                WishlistBadge: "Wishlist: 2"
WishlistPage lists both; remove "Running Shoes" -> WishlistBadge: "Wishlist: 1"
calling useWishlistStore() outside any WishlistStoreProvider -> throws a clear error

๐Ÿ’ก Hint: this is examples/06_reducer_context_preview.jsx end to end, renamed to a new domain - one useReducer call lives inside the provider, { wishlist, dispatch } travels down through context, and the safety-throw custom hook is the one piece of error handling this whole pattern needs.

Show the solutions for Part 10 (12 files)

solutions/ex01_seat_quantity_stepper.jsx

import { useReducer } from "react";

const MIN_SEATS = 1;
const MAX_SEATS = 6;

export function seatQuantityReducer(state, action) {
  switch (action.type) {
    case "increment":
      return { quantity: Math.min(MAX_SEATS, state.quantity + 1) };
    case "decrement":
      return { quantity: Math.max(MIN_SEATS, state.quantity - 1) };
    case "reset":
      return { quantity: MIN_SEATS };
    default:
      throw new Error(`Unknown action type: ${action.type}`);
  }
}

export function SeatQuantityStepper() {
  const [state, dispatch] = useReducer(seatQuantityReducer, { quantity: MIN_SEATS });

  return (
    <div>
      <p>Quantity: {state.quantity}</p>
      <button onClick={() => dispatch({ type: "decrement" })}>-</button>
      <button onClick={() => dispatch({ type: "increment" })}>+</button>
      <button onClick={() => dispatch({ type: "reset" })}>Reset to 1</button>
    </div>
  );
}

solutions/ex01_seat_quantity_stepper.test.jsx

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import { SeatQuantityStepper, seatQuantityReducer } from "./ex01_seat_quantity_stepper.jsx";

describe("seatQuantityReducer: tested directly, as a plain function", () => {
  it("really caps increment at 6 and decrement at 1", () => {
    expect(seatQuantityReducer({ quantity: 6 }, { type: "increment" })).toEqual({ quantity: 6 });
    expect(seatQuantityReducer({ quantity: 1 }, { type: "decrement" })).toEqual({ quantity: 1 });
  });

  it("really resets to 1 regardless of the current quantity", () => {
    expect(seatQuantityReducer({ quantity: 5 }, { type: "reset" })).toEqual({ quantity: 1 });
  });
});

describe("SeatQuantityStepper: wired with useReducer", () => {
  it("really increments, caps at 6, decrements, and resets", async () => {
    const user = userEvent.setup();
    render(<SeatQuantityStepper />);

    expect(screen.getByText("Quantity: 1")).toBeInTheDocument();

    for (let i = 0; i < 5; i += 1) {
      await user.click(screen.getByRole("button", { name: "+" }));
    }
    expect(screen.getByText("Quantity: 6")).toBeInTheDocument();

    await user.click(screen.getByRole("button", { name: "+" }));
    expect(screen.getByText("Quantity: 6")).toBeInTheDocument();

    await user.click(screen.getByRole("button", { name: "-" }));
    await user.click(screen.getByRole("button", { name: "-" }));
    expect(screen.getByText("Quantity: 4")).toBeInTheDocument();

    await user.click(screen.getByRole("button", { name: "Reset to 1" }));
    expect(screen.getByText("Quantity: 1")).toBeInTheDocument();
  });
});

solutions/ex02_passenger_list.jsx

import { useReducer, useState } from "react";

export function passengerReducer(state, action) {
  switch (action.type) {
    case "add": {
      const name = action.name.trim();
      if (name === "") {
        return state;
      }
      const alreadyListed = state.passengers.some((existing) => existing.toLowerCase() === name.toLowerCase());
      if (alreadyListed) {
        return state;
      }
      return { passengers: [...state.passengers, name] };
    }
    case "remove":
      return { passengers: state.passengers.filter((_, index) => index !== action.index) };
    default:
      throw new Error(`Unknown action type: ${action.type}`);
  }
}

export function PassengerList() {
  const [state, dispatch] = useReducer(passengerReducer, { passengers: [] });
  const [nameInput, setNameInput] = useState("");

  function handleAdd() {
    dispatch({ type: "add", name: nameInput });
    setNameInput("");
  }

  return (
    <div>
      <label htmlFor="passenger-name">Passenger name</label>
      <input id="passenger-name" value={nameInput} onChange={(event) => setNameInput(event.target.value)} />
      <button onClick={handleAdd}>Add passenger</button>

      <ul>
        {state.passengers.map((name, index) => (
          <li key={`${name}-${index}`}>
            {name}
            <button onClick={() => dispatch({ type: "remove", index })}>{`Remove ${name}`}</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

solutions/ex02_passenger_list.test.jsx

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import { PassengerList, passengerReducer } from "./ex02_passenger_list.jsx";

describe("passengerReducer: tested directly", () => {
  it("really rejects a blank name and a case-insensitive duplicate, unchanged", () => {
    const withAsha = passengerReducer({ passengers: [] }, { type: "add", name: "Asha" });
    expect(withAsha.passengers).toEqual(["Asha"]);

    const afterBlank = passengerReducer(withAsha, { type: "add", name: "   " });
    expect(afterBlank).toBe(withAsha); // unchanged - same reference back

    const afterDuplicate = passengerReducer(withAsha, { type: "add", name: "asha" });
    expect(afterDuplicate).toBe(withAsha);
  });
});

describe("PassengerList: a controlled input wired to the reducer", () => {
  it("really adds unique names, rejects blanks and case-insensitive duplicates, and removes by name", async () => {
    const user = userEvent.setup();
    render(<PassengerList />);

    const input = screen.getByLabelText("Passenger name");
    const addButton = screen.getByRole("button", { name: "Add passenger" });

    await user.type(input, "Asha");
    await user.click(addButton);
    expect(screen.getByText("Asha")).toBeInTheDocument();

    await user.type(input, "asha");
    await user.click(addButton);
    expect(screen.getAllByText("Asha")).toHaveLength(1); // still only one entry

    await user.type(input, "   ");
    await user.click(addButton);
    expect(screen.queryByText("   ")).not.toBeInTheDocument();

    await user.type(input, "Rohan");
    await user.click(addButton);
    expect(screen.getByText("Rohan")).toBeInTheDocument();

    await user.click(screen.getByRole("button", { name: "Remove Asha" }));
    expect(screen.queryByText("Asha")).not.toBeInTheDocument();
    expect(screen.getByText("Rohan")).toBeInTheDocument();
  });
});

solutions/ex03_order_items_mutation_bug.jsx

// A teammate's version mutates the matched item in place and returns the
// exact same `state` reference - which is sometimes invisible to the UI
// (another, unrelated rerender happens to redraw it anyway) and sometimes
// not, depending entirely on what else is going on. That is what makes
// this bug intermittent instead of consistently broken.
export function orderItemsReducerBroken(state, action) {
  if (action.type === "markReady") {
    const item = state.items.find((i) => i.id === action.id);
    if (item) {
      item.status = "ready"; // mutates the object in place
    }
    return state; // same reference - React can treat this as "no change"
  }
  return state;
}

export function orderItemsReducerFixed(state, action) {
  if (action.type === "markReady") {
    return {
      items: state.items.map((item) => (item.id === action.id ? { ...item, status: "ready" } : item)),
    };
  }
  return state;
}

solutions/ex03_order_items_mutation_bug.test.jsx

import { describe, expect, it } from "vitest";
import { orderItemsReducerBroken, orderItemsReducerFixed } from "./ex03_order_items_mutation_bug.jsx";

describe("orderItemsReducerBroken vs orderItemsReducerFixed: proving the mutation", () => {
  it("really mutates the original state object in the broken version", () => {
    const originalState = { items: [{ id: "o1", status: "pending" }] };

    const result = orderItemsReducerBroken(originalState, { type: "markReady", id: "o1" });

    // The function "worked" in the sense that the item is now ready - but
    // the ORIGINAL object passed in was changed too, and the same
    // reference was handed back.
    expect(originalState.items[0].status).toBe("ready");
    expect(result).toBe(originalState);
  });

  it("really leaves the original state object untouched in the fixed version", () => {
    const originalState = { items: [{ id: "o1", status: "pending" }] };

    const result = orderItemsReducerFixed(originalState, { type: "markReady", id: "o1" });

    expect(originalState.items[0].status).toBe("pending"); // untouched
    expect(result.items[0].status).toBe("ready"); // the new state has the update
    expect(result).not.toBe(originalState);
    expect(result.items).not.toBe(originalState.items);
  });
});

solutions/ex04_recently_viewed_widget.jsx

import { useReducer } from "react";

const MAX_RECENTLY_VIEWED = 5;

export const loadCallCounts = {};

export function loadRecentlyViewed(storageKey) {
  loadCallCounts[storageKey] = (loadCallCounts[storageKey] ?? 0) + 1;
  try {
    const stored = window.localStorage.getItem(storageKey);
    return stored !== null ? JSON.parse(stored) : { productIds: [] };
  } catch {
    return { productIds: [] };
  }
}

export function recentlyViewedReducer(state, action) {
  switch (action.type) {
    case "view": {
      const withoutThisProduct = state.productIds.filter((id) => id !== action.productId);
      return { productIds: [action.productId, ...withoutThisProduct].slice(0, MAX_RECENTLY_VIEWED) };
    }
    default:
      throw new Error(`Unknown action type: ${action.type}`);
  }
}

export function RecentlyViewedWidget({ storageKey }) {
  const [state, dispatch] = useReducer(recentlyViewedReducer, storageKey, loadRecentlyViewed);

  return (
    <div>
      <p>Recently viewed: {state.productIds.join(", ") || "none yet"}</p>
      <button onClick={() => dispatch({ type: "view", productId: "P100" })}>View P100</button>
    </div>
  );
}

solutions/ex04_recently_viewed_widget.test.jsx

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import { RecentlyViewedWidget, loadCallCounts } from "./ex04_recently_viewed_widget.jsx";

describe("RecentlyViewedWidget: lazy init restores once, viewing dedupes and caps at 5", () => {
  it("really restores the saved list on mount, and never re-runs the loader on later clicks", async () => {
    const key = "recently-viewed:ex04-test";
    window.localStorage.setItem(key, JSON.stringify({ productIds: ["P1", "P2"] }));

    const user = userEvent.setup();
    render(<RecentlyViewedWidget storageKey={key} />);

    expect(screen.getByText("Recently viewed: P1, P2")).toBeInTheDocument();
    expect(loadCallCounts[key]).toBe(1);

    await user.click(screen.getByRole("button", { name: "View P100" }));
    await user.click(screen.getByRole("button", { name: "View P100" }));
    await user.click(screen.getByRole("button", { name: "View P100" }));

    // P100 moves to the front and is never duplicated by the repeated clicks.
    expect(screen.getByText("Recently viewed: P100, P1, P2")).toBeInTheDocument();
    expect(loadCallCounts[key]).toBe(1);
  });
});

solutions/ex05_dispatch_through_memo.jsx

// oxlint flags every renderCountRef.current read/write below as
// react(refs) - the same deliberate exception
// part-06-useeffect-and-side-effects/examples/04_derived_state_antipattern.jsx
// uses: a render counter is this exercise's own proof mechanism, not a
// pattern to copy into real component code.
import { memo, useReducer, useState } from "react";

export function orderReducer(state, action) {
  switch (action.type) {
    case "refresh":
      return { ...state, refreshedCount: state.refreshedCount + 1 };
    case "cancel":
      return { ...state, cancelled: true };
    default:
      throw new Error(`Unknown action type: ${action.type}`);
  }
}

// dispatch is stable across renders (Section 6), and renderCountRef is the
// exact same object every render too - React.memo's default shallow prop
// comparison sees nothing changed, so this never re-renders just because
// OrderDashboard did.
export const RefreshButton = memo(function RefreshButton({ dispatch, renderCountRef }) {
  renderCountRef.current += 1;
  return <button onClick={() => dispatch({ type: "refresh" })}>Refresh</button>;
});

// onCancel is a brand-new arrow function created inside OrderDashboard on
// every single render - React.memo's shallow comparison sees a changed
// prop every time, so this re-renders on every parent render regardless.
export const BrokenButton = memo(function BrokenButton({ onCancel, renderCountRef }) {
  renderCountRef.current += 1;
  return <button onClick={onCancel}>Cancel</button>;
});

export function OrderDashboard({ refreshRenderCountRef, cancelRenderCountRef }) {
  const [, dispatch] = useReducer(orderReducer, { refreshedCount: 0, cancelled: false });
  const [tick, setTick] = useState(0);

  return (
    <div>
      <p>Tick: {tick}</p>
      <button onClick={() => setTick((current) => current + 1)}>Force tick</button>
      <RefreshButton dispatch={dispatch} renderCountRef={refreshRenderCountRef} />
      <BrokenButton onCancel={() => dispatch({ type: "cancel" })} renderCountRef={cancelRenderCountRef} />
    </div>
  );
}

solutions/ex05_dispatch_through_memo.test.jsx

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import { OrderDashboard } from "./ex05_dispatch_through_memo.jsx";

describe("OrderDashboard: dispatch through a memoized child vs a fresh inline handler", () => {
  it("really skips re-rendering the dispatch-fed child, and re-renders the inline-handler child every time", async () => {
    const user = userEvent.setup();
    const refreshRenderCountRef = { current: 0 };
    const cancelRenderCountRef = { current: 0 };

    render(<OrderDashboard refreshRenderCountRef={refreshRenderCountRef} cancelRenderCountRef={cancelRenderCountRef} />);
    expect(refreshRenderCountRef.current).toBe(1);
    expect(cancelRenderCountRef.current).toBe(1);

    const forceTick = screen.getByRole("button", { name: "Force tick" });
    await user.click(forceTick);
    await user.click(forceTick);
    await user.click(forceTick);

    expect(screen.getByText("Tick: 3")).toBeInTheDocument();

    // RefreshButton received the stable `dispatch` plus the same ref
    // object every render - React.memo's shallow comparison sees nothing
    // changed, so it never rendered again after the first time.
    expect(refreshRenderCountRef.current).toBe(1);

    // BrokenButton received a brand-new arrow function every render -
    // React.memo sees a changed prop every time and re-renders in step
    // with the parent (1 initial + 3 ticks).
    expect(cancelRenderCountRef.current).toBe(4);
  });
});

solutions/ex06_wishlist_store.jsx

import { createContext, useContext, useReducer } from "react";

export function wishlistReducer(state, action) {
  switch (action.type) {
    case "add": {
      const alreadyWishlisted = state.items.some((item) => item.id === action.product.id);
      if (alreadyWishlisted) {
        return state;
      }
      return { items: [...state.items, action.product] };
    }
    case "remove":
      return { items: state.items.filter((item) => item.id !== action.id) };
    case "clear":
      return { items: [] };
    default:
      throw new Error(`Unknown action type: ${action.type}`);
  }
}

const WishlistStoreContext = createContext(undefined);

export function WishlistStoreProvider({ children }) {
  const [wishlist, dispatch] = useReducer(wishlistReducer, { items: [] });
  return <WishlistStoreContext.Provider value={{ wishlist, dispatch }}>{children}</WishlistStoreContext.Provider>;
}

export function useWishlistStore() {
  const store = useContext(WishlistStoreContext);
  if (store === undefined) {
    throw new Error("useWishlistStore must be called inside a <WishlistStoreProvider>");
  }
  return store;
}

export function WishlistAddControl({ product }) {
  const { dispatch } = useWishlistStore();
  return <button onClick={() => dispatch({ type: "add", product })}>{`Add ${product.name} to wishlist`}</button>;
}

export function WishlistBadge() {
  const { wishlist } = useWishlistStore();
  return <p>{`Wishlist: ${wishlist.items.length}`}</p>;
}

export function WishlistPage() {
  const { wishlist, dispatch } = useWishlistStore();
  return (
    <ul>
      {wishlist.items.map((item) => (
        <li key={item.id}>
          {item.name}
          <button onClick={() => dispatch({ type: "remove", id: item.id })}>{`Remove ${item.name}`}</button>
        </li>
      ))}
    </ul>
  );
}

solutions/ex06_wishlist_store.test.jsx

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
  WishlistAddControl,
  WishlistBadge,
  WishlistPage,
  WishlistStoreProvider,
  useWishlistStore,
} from "./ex06_wishlist_store.jsx";

const RUNNING_SHOES = { id: "p1", name: "Running Shoes" };
const YOGA_MAT = { id: "p2", name: "Yoga Mat" };

describe("WishlistStoreProvider: one reducer, shared through context, no prop drilling", () => {
  it("really dedupes on add and keeps every consuming component in sync", async () => {
    const user = userEvent.setup();
    render(
      <WishlistStoreProvider>
        <WishlistAddControl product={RUNNING_SHOES} />
        <WishlistAddControl product={YOGA_MAT} />
        <WishlistBadge />
        <WishlistPage />
      </WishlistStoreProvider>,
    );

    expect(screen.getByText("Wishlist: 0")).toBeInTheDocument();

    await user.click(screen.getByRole("button", { name: "Add Running Shoes to wishlist" }));
    await user.click(screen.getByRole("button", { name: "Add Running Shoes to wishlist" }));
    expect(screen.getByText("Wishlist: 1")).toBeInTheDocument(); // deduplicated

    await user.click(screen.getByRole("button", { name: "Add Yoga Mat to wishlist" }));
    expect(screen.getByText("Wishlist: 2")).toBeInTheDocument();

    await user.click(screen.getByRole("button", { name: "Remove Running Shoes" }));
    expect(screen.getByText("Wishlist: 1")).toBeInTheDocument();
    expect(screen.queryByText("Running Shoes")).not.toBeInTheDocument();
    expect(screen.getByText("Yoga Mat")).toBeInTheDocument();
  });

  describe("useWishlistStore outside a provider", () => {
    beforeEach(() => {
      vi.spyOn(console, "error").mockImplementation(() => {});
    });

    afterEach(() => {
      console.error.mockRestore();
    });

    it("really throws a clear error", () => {
      function Rogue() {
        useWishlistStore();
        return null;
      }

      expect(() => render(<Rogue />)).toThrow("useWishlistStore must be called inside a <WishlistStoreProvider>");
    });
  });
});

Common mistakes

Mistake Why it is wrong Fix
Mutating state (or something inside it) directly inside a reducer, e.g. state.items.push(newItem); return state; React compares the previous and next state by reference; returning the same mutated object looks like "nothing changed," so the UI silently fails to re-render even though the data did change Always return a brand-new object/array built with spread, map, or filter - never mutate state or anything nested inside it (Section 3)
Letting a reducer's default case silently return state unchanged for an unrecognized action type A typo'd type string ("ad" instead of "add") becomes "nothing happens," which is far harder to debug than a crash Throw in the default case, so a typo fails loudly during development instead of quietly doing nothing (Section 2)
Keeping several useState calls that all describe one piece of UI state, updating them across separately-written handlers Nothing enforces that every handler updates every related piece - one omission anywhere and the pieces drift out of sync with no syntax error to catch it (Section 1) Collapse the related pieces into one state value, updated through one reducer with named action types, in one place (Sections 2-4)
Passing an expensive-to-compute value as useReducer's second argument directly, e.g. useReducer(reducer, loadInitialCart(key)) That expression is evaluated on every render, even though only the very first render's result is ever kept - the same waste a non-lazy useState initializer causes Pass the raw argument as the second parameter and the function itself as the third - useReducer(reducer, key, loadInitialCart) - so React calls it exactly once (Section 5)
Assuming a plain inline handler defined inside a component is "just as stable" as dispatch for a dependency array or a memoized child's props A function literal written inside the component body is a brand-new function object every render - comparing it by reference always reports "changed" Only dispatch (and anything wrapped in useCallback, Part 12) comes with React's stable-identity guarantee; treat a plain inline handler as a new value every render (Section 6)

Quick recap

  • Several useState calls that all describe one idea can drift out of sync the moment one handler updates some of them but not all - a reducer collapses that into one state value and one update function.
  • An action is a plain object naming what happened ({ type, ...payload }); only the reducer decides what the new state is, and it does so as a pure function - same state + action in, same new state out, nothing mutated.
  • useReducer(reducer, initialArg, init?) returns [state, dispatch]; dispatch takes an action, never a new state directly, and its own identity never changes across a component's re-renders.
  • The optional third argument computes the real initial state by calling init(initialArg) exactly once, on mount - the reducer's equivalent of useState's lazy initializer function.
  • useReducer previews cleanly into context: one reducer behind one Provider, read through one custom hook, shared by any number of descendants with no prop drilling - the shape Part 9 (context) and this part (reducers) combine into, and the shape this stage's project builds for real.
  • A reducer's biggest practical win is testability: it is a plain function, so its update logic can be tested by calling it directly, with no component rendered at all.

Checklist

  • I can explain, in one sentence, the problem that made BuggyCartMultiState drift, and why a reducer fixes it.
  • I wrote (or read closely) a pure reducer with at least three action types, where every branch returns a new object/array without mutating the state it received.
  • I wired a reducer into a component with useReducer, dispatching actions from event handlers instead of calling a setter with a precomputed new value.
  • I used useReducer's third argument to compute an initial state lazily, and proved - the way examples/04_lazy_init.test.jsx does - that the init function runs once, not once per render.
  • I proved dispatch's identity is stable across a re-render by comparing two captured references with ===, and contrasted it with a plain inline handler that is not.
  • I can describe, in one or two sentences, how a reducer and context combine - one useReducer call inside a Provider, read through a custom hook - without needing to write the full context plumbing again (that's Part 9).
  • I tested a reducer by calling it directly with a state and an action, with no render() anywhere in that test.

Search the guide