Course contentsShow
← React
Lesson 1693 of 2,39641. State Management EcosystemFree lesson

Context + useReducer for Complex Local State

Combine Context with useReducer to manage complex state without external libraries.

Context + useReducer for Complex Local State

What you'll learn: How to combine Context API with useReducer to manage sophisticated state logic without reaching for external libraries like Redux.

The Problem with Complex Local State

When your component state involves multiple related values, complex update logic, or predictable state transitions, useState becomes unwieldy. You end up with multiple state setters, interdependent updates, and scattered logic.

The Solution: useReducer + Context

By pairing useReducer (which centralizes state logic) with Context (which distributes state access), you create a powerful local state management system:

  • useReducer handles the "how" — all state transitions in one reducer function
  • Context handles the "where" — makes state and dispatch available anywhere in your tree

The Pattern

Create a context that provides both state and dispatch:

const CartContext = createContext();

function cartReducer(state, action) {
  switch (action.type) {
    case 'ADD_ITEM':
      return { ...state, items: [...state.items, action.payload] };
    case 'REMOVE_ITEM':
      return { ...state, items: state.items.filter(i => i.id !== action.payload) };
    case 'CLEAR':
      return { items: [], total: 0 };
    default:
      return state;
  }
}

function CartProvider({ children }) {
  const [state, dispatch] = useReducer(cartReducer, { items: [], total: 0 });
  
  return (
    <CartContext.Provider value={{ state, dispatch }}>
      {children}
    </CartContext.Provider>
  );
}

Components consume the context and dispatch actions:

function AddToCart({ product }) {
  const { dispatch } = useContext(CartContext);
  
  return (
    <button onClick={() => dispatch({ type: 'ADD_ITEM', payload: product })}>
      Add to Cart
    </button>
  );
}

When to Use This

This pattern shines for feature-specific state (shopping cart, multi-step form, game state) that's too complex for useState but doesn't need Redux's global scope or middleware.

Key Takeaway: Combining Context with useReducer gives you Redux-like predictability and organization for complex local state, keeping logic centralized while avoiding prop drilling — no external library required.