Course contentsShow
← React
Lesson 2324 of 2,39650. Performance: Optimization TechniquesFree lesson

Separating State and Dispatch Contexts

Using one context for state and another for updaters to prevent re-renders in components that only call actions.

Separating State and Dispatch Contexts

What you'll learn: How to split state and updater functions into separate contexts to prevent unnecessary re-renders in components that only dispatch actions.

The Core Problem

When you put both state and updater functions in the same context value, every component consuming that context re-renders whenever the state changes—even if that component only calls the updater and never reads the state itself.

This happens because the context object reference changes on every state update, triggering re-renders in all consumers.

The Solution: Two Contexts

Create two separate contexts from the same source:

  1. StateContext - holds the actual state value
  2. DispatchContext - holds the updater functions (or dispatch function)

Components that only need to call actions consume DispatchContext. Since the dispatch function reference stays stable across renders, these components won't re-render when state changes.

Components that read state consume StateContext and accept the re-render cost—but now it's isolated to only the components that actually need the new state.

The Pattern

Think of it like separating a read-only view from a write-only remote control. Viewers re-render when the screen changes. Remote holders don't care what's on screen—they just change channels when pressed.

const StateContext = createContext();
const DispatchContext = createContext();

function Provider({ children }) {
  const [state, dispatch] = useReducer(reducer, initial);
  
  return (
    <DispatchContext.Provider value={dispatch}>
      <StateContext.Provider value={state}>
        {children}
      </StateContext.Provider>
    </DispatchContext.Provider>
  );
}

Components calling useContext(DispatchContext) only re-render when they change, not when state updates.

Key Takeaway: Separating state and dispatch into two contexts prevents re-renders in action-only components, optimizing performance when many components trigger updates but few need to read the changing state.