Why Splitting Contexts Matters for Performance
You'll learn: How separating state and dispatch into different contexts prevents unnecessary re-renders in components that only dispatch actions.
The Performance Problem with Single Context
When you combine state and dispatch in one context (like <AppContext.Provider value={{ state, dispatch }}>), every component that consumes that context re-renders whenever the state changes—even if that component only uses dispatch and never reads the state.
This happens because the context value is a new object on every render, and React treats any context value change as a reason to re-render all consumers.
The Solution: Split State and Dispatch
By creating two separate contexts—one for state, one for dispatch—you gain fine-grained control:
- Components that only read state subscribe to
StateContext - Components that only dispatch actions subscribe to
DispatchContext
The key insight: dispatch is a stable function that never changes between renders. So components that only consume DispatchContext won't re-render when state updates, because dispatch itself hasn't changed.
Real-World Analogy
Think of a restaurant: the menu (state) changes daily, and the ordering system (dispatch) stays constant. If you're a chef who only receives orders through dispatch, you don't need to be notified every time the menu changes. You only care when a new order arrives.
Why This Matters
For components deep in your tree that only dispatch actions (like form submission buttons or action toolbars), splitting contexts eliminates wasteful re-renders. The state context can change freely without triggering updates in dispatch-only consumers.
Key Takeaway: Splitting state and dispatch into separate contexts allows components that only dispatch actions to avoid re-rendering when state changes, significantly improving performance in large applications.