Read-Only vs Write-Only Context Split
What you'll learn: How to separate your context into two — one for state values and one for update functions — to prevent unnecessary re-renders.
The Problem with Combined Context
When you put both state and update functions in the same context value, every consumer re-renders whenever the state changes — even components that only call update functions and never read the state. This wastes rendering cycles.
The Split Pattern
Create two separate contexts from the same provider:
- Read Context: Holds the actual state values
- Write Context: Holds the dispatch function or setter functions
Components that only read state subscribe to the Read Context. Components that only update state subscribe to the Write Context. Since the dispatch function never changes (it's stable), Write Context consumers never re-render when state updates.
The Analogy
Think of a library: the reading room (Read Context) gets crowded every time new books arrive. The return desk (Write Context) stays quiet — you can drop off books without being affected by activity in the reading room. Splitting them prevents unnecessary congestion.
Why This Works
The dispatch function from useReducer is stable across renders. By placing it in its own context, components that only dispatch actions won't re-render when the state they're updating changes. They're invisible to those updates — they just send instructions and move on.
This pattern shines when you have form inputs or buttons that trigger updates but don't display the current state themselves.
Key Takeaway: Splitting context into read-only (state) and write-only (dispatch) contexts lets update-only components avoid re-renders, optimizing performance for complex state trees.