Creating the Context Pair: State and Dispatch
What you'll learn: How to create two separate contexts for state and dispatch to optimize performance and prevent unnecessary re-renders in your component tree.
The Problem with Single Context
When you combine useReducer with Context, you might be tempted to pass both state and dispatch in one context value:
const AppContext = createContext();
function AppProvider({ children }) {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<AppContext.Provider value={{ state, dispatch }}>
{children}
</AppContext.Provider>
);
}
The issue? Every component consuming this context re-renders whenever state changes—even if they only need dispatch (which never changes).
The Two-Context Solution
Split them into separate contexts:
const StateContext = createContext();
const DispatchContext = createContext();
function AppProvider({ children }) {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<StateContext.Provider value={state}>
<DispatchContext.Provider value={dispatch}>
{children}
</DispatchContext.Provider>
</StateContext.Provider>
);
}
Now components can subscribe selectively:
// Only re-renders when state changes
function DisplayComponent() {
const state = useContext(StateContext);
return <div>{state.count}</div>;
}
// Never re-renders (dispatch is stable)
function ButtonComponent() {
const dispatch = useContext(DispatchContext);
return <button onClick={() => dispatch({ type: 'INCREMENT' })}>+</button>;
}
The Analogy
Think of a restaurant: the StateContext is the menu board that changes daily (you check it to see what's available), while DispatchContext is the ordering counter—it never moves. You don't need to watch the counter for changes; you just need to know where it is.
Key Takeaway: Creating separate contexts for state and dispatch allows components to consume only what they need, preventing unnecessary re-renders and improving performance in your context-based state management system.