Course contentsShow
← React
Lesson 779 of 2,39620. useReducerFree lesson

The Provider Component Pattern

Wrapping useReducer in a provider component that exposes both state and dispatch contexts to the tree below.

The Provider Component Pattern

What you'll learn: How to wrap useReducer with a provider component that supplies both state and dispatch to all children through context.

The Two-Context Structure

Once you've created your state and dispatch contexts, you need a provider component that does the actual work. This component:

  1. Creates the reducer with useReducer
  2. Provides the state value to one context
  3. Provides the dispatch function to another context
  4. Wraps all children that need access

Think of it like a distribution hub: the provider component is the warehouse that receives deliveries (actions) and stocks the shelves (state), while context is the delivery network that carries goods to individual stores (components).

Basic Pattern

function TodoProvider({ children }: { children: React.ReactNode }) {
  const [state, dispatch] = useReducer(todoReducer, initialState);

  return (
    <TodoStateContext.Provider value={state}>
      <TodoDispatchContext.Provider value={dispatch}>
        {children}
      </TodoDispatchContext.Provider>
    </TodoStateContext.Provider>
  );
}

Why This Pattern Works

By creating a dedicated provider component, you:

  • Encapsulate the reducer initialization logic in one place
  • Avoid prop drilling through intermediate components
  • Co-locate state management with its distribution mechanism
  • Reuse the same provider across different parts of your app

The children prop makes this component a wrapper — any component tree you nest inside gets automatic access to both state and dispatch through their respective contexts.

Key Takeaway: The provider component pattern combines useReducer with two context providers, creating a reusable wrapper that distributes both state and dispatch functions to all descendants without prop drilling.