Skip to the content

Lesson 169 of 296

useReducer and useContext

What you will learn

  • useReducer for complex state logic
  • Writing reducers with discriminated unions
  • Context for sharing values deeply
  • Context and performance
  • Combining reducer and context
On this page

useReducer

When state has several related parts or many ways to change, put the update logic in one reducer function:

(currentState, action) => newState

An action describes what happened. The reducer decides how the state changes.

TSX
import { useReducer } from "react";

type CartItem = { sku: string; name: string; pricePence: number; qty: number };
type CartState = { items: CartItem[] };

type CartAction =
  | { type: "add"; item: Omit<CartItem, "qty"> }
  | { type: "remove"; sku: string }
  | { type: "setQty"; sku: string; qty: number }
  | { type: "clear" };

function cartReducer(state: CartState, action: CartAction): CartState {
  switch (action.type) {
    case "add": {
      const existing = state.items.find((i) => i.sku === action.item.sku);
      if (existing) {
        return {
          items: state.items.map((i) =>
            i.sku === action.item.sku ? { ...i, qty: i.qty + 1 } : i
          )
        };
      }
      return { items: [...state.items, { ...action.item, qty: 1 }] };
    }
    case "remove":
      return { items: state.items.filter((i) => i.sku !== action.sku) };
    case "setQty":
      if (action.qty <= 0) return { items: state.items.filter((i) => i.sku !== action.sku) };
      return {
        items: state.items.map((i) => (i.sku === action.sku ? { ...i, qty: action.qty } : i))
      };
    case "clear":
      return { items: [] };
  }
}

function cartTotalPence(state: CartState): number {
  return state.items.reduce((sum, i) => sum + i.pricePence * i.qty, 0);
}

function CartWidget() {
  const [cart, dispatch] = useReducer(cartReducer, { items: [] });
  return (
    <div>
      <button
        type="button"
        onClick={() => dispatch({ type: "add", item: { sku: "MUG", name: "Mug", pricePence: 499 } })}
      >
        Add mug
      </button>
      <p>{cart.items.length} lines, total {cartTotalPence(cart)}p</p>
      <button type="button" onClick={() => dispatch({ type: "clear" })}>Clear</button>
    </div>
  );
}
  • dispatch(action) sends an action. React calls the reducer and re-renders with the result.
  • The reducer is a pure function (Lesson 38): easy to unit test without React at all.
  • The actions are a discriminated union (Lesson 107), so TypeScript checks every case and every field.
  • dispatch never changes identity, so it is safe to pass down.

useState or useReducer?

useStateuseReducer
Simple, independent valuesRelated values updated together
Few kinds of updatesMany kinds of updates
Logic in the componentLogic in one pure, testable function

Context

Context passes a value to any component below a provider, without prop drilling.

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

type Theme = "light" | "dark";
type ThemeContextValue = { theme: Theme; toggle: () => void };

const ThemeContext = createContext<ThemeContextValue | null>(null);

function ThemeProvider({ children }: { children: ReactNode }) {
  const [theme, setTheme] = useState<Theme>("light");
  const value = useMemo(
    () => ({ theme, toggle: () => setTheme((t) => (t === "light" ? "dark" : "light")) }),
    [theme]
  );
  return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
}

function useTheme(): ThemeContextValue {
  const context = useContext(ThemeContext);
  if (context === null) throw new Error("useTheme must be used inside ThemeProvider");
  return context;
}

function ThemeToggle() {
  const { theme, toggle } = useTheme();
  return <button type="button" onClick={toggle}>Theme: {theme}</button>;
}
  • createContext(null) with a custom useTheme hook that throws gives a clear error if someone forgets the provider, and removes null from the type.
  • In React 19 you can also write <ThemeContext value={value}> without .Provider.

Context and performance

When the provider's value changes, every component using that context re-renders. Tips:

  • Memoise the value object (as above). Without useMemo, a new object every render makes every consumer re-render.
  • Split contexts: put rarely changing values (user, theme) and frequently changing values (a live counter) in separate contexts.
  • Context is great for low-frequency global values: theme, language, current user, feature flags. For frequently changing global state, a state library (Lesson 174) is usually more efficient.

Reducer + context

For a medium-sized shared state, combine them: keep state with useReducer in a provider, and expose state and dispatch through context (often two separate contexts, so components that only dispatch do not re-render when state changes). This is a simple built-in alternative to Redux.

How to say it in an interview

"useReducer moves update logic into a pure reducer that takes state and an action and returns new state, which suits related state with many kinds of updates and is easy to unit test; I type actions as a discriminated union. Context passes values deeply without prop drilling. Every consumer re-renders when the provider value changes, so I memoise the value, split contexts by update frequency, and use context mainly for low-frequency values like theme and current user, with a custom hook that throws if the provider is missing."

Key words

WordMeaning
ReducerA pure function (state, action) => newState
ActionAn object describing what happened
dispatchSends an action to the reducer
ContextShares a value with every component below a provider
ProviderThe component that supplies a context value

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.