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:
- Creates the reducer with
useReducer - Provides the
statevalue to one context - Provides the
dispatchfunction to another context - 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.