Skip to content

Context + Reducer State Management

Medium ~40 min

What you'll build

A cart with add/remove/update-quantity operations, managed by a reducer and shared via Context so any component can access or update it.

Goals

  • Define a reducer with typed actions
  • Create a Context provider wrapping the reducer
  • Consume context with a custom hook
  • Avoid prop drilling through deep component trees

Prerequisites

  • useState and useEffect
  • React Context basics
  • Array methods (filter, map, find)

Steps

  1. 1

    Define the reducer

    A reducer is a function (state, action) => newState. Define the cart state (array of items) and actions: ADD, REMOVE, UPDATE_QTY.

    Code
    const cartReducer = (state, action) => {
      switch (action.type) {
        case 'ADD':
          const existing = state.find(i => i.id === action.item.id);
          if (existing) {
            return state.map(i => i.id === action.item.id
              ? { ...i, qty: i.qty + 1 } : i);
          }
          return [...state, { ...action.item, qty: 1 }];
        case 'REMOVE':
          return state.filter(i => i.id !== action.id);
        case 'UPDATE_QTY':
          return state.map(i => i.id === action.id
            ? { ...i, qty: action.qty } : i).filter(i => i.qty > 0);
        default:
          return state;
      }
    };

    Expected result

    The reducer handles all three actions immutably.

  2. 2

    Create the Context provider

    Create a CartContext and a CartProvider component that wraps useReducer and passes state and dispatch via context value.

    Code
    import { createContext, useContext, useReducer } from 'react';
    
    const CartContext = createContext(null);
    
    export function CartProvider({ children }) {
      const [cart, dispatch] = useReducer(cartReducer, []);
      return (
        <CartContext.Provider value={{ cart, dispatch }}>
          {children}
        </CartContext.Provider>
      );
    }

    Expected result

    Any child of CartProvider can access the cart.

  3. 3

    Create a useCart hook

    Create a custom hook that consumes the context and throws if used outside the provider. This gives a clean API and catches mistakes early.

    Code
    export function useCart() {
      const ctx = useContext(CartContext);
      if (!ctx) throw new Error('useCart must be used within CartProvider');
      return ctx;
    }

    Expected result

    Components call useCart() to get { cart, dispatch }.

  4. 4

    Build cart UI components

    Create a ProductList, CartItem, and CartSummary component. Each uses useCart() to read or update the cart — no props needed for cart data.

    Code
    function ProductList({ products }) {
      const { dispatch } = useCart();
      return products.map(p => (
        <div key={p.id}>
          {p.name} - ${p.price}
          <button onClick={() => dispatch({ type: 'ADD', item: p })}>
            Add to Cart
          </button>
        </div>
      ));
    }
    
    function CartSummary() {
      const { cart } = useCart();
      const total = cart.reduce((sum, i) => sum + i.price * i.qty, 0);
      return <div>Total: ${total}</div>;
    }

    Expected result

    Products add to cart; summary updates total — all without prop drilling.

  5. 5

    Wire it all together

    Wrap the app in CartProvider and render the components. Test the full flow: add items, update quantities, remove items, verify total.

    Code
    function App() {
      return (
        <CartProvider>
          <ProductList products={sampleProducts} />
          <CartSummary />
        </CartProvider>
      );
    }

    Expected result

    The app works end-to-end with shared cart state via Context.

Try it yourself

What you learned

You built scalable state management with Context + Reducer — the standard pattern for medium-sized React apps before reaching for Redux or Zustand.

Related Resources

Related Lessons

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to topic