Course contentsShow
← React
Lesson 2377 of 2,39651. TypeScript with React BasicsFree lesson

Separating State and Dispatch Contexts

The pattern of splitting state and dispatch into separate contexts for better performance and cleaner types.

Separating State and Dispatch Contexts

What you'll learn: How splitting state and dispatch into separate contexts prevents unnecessary re-renders and creates cleaner TypeScript types.

The Core Problem

When you provide both state and dispatch in a single context value, every component that consumes that context re-renders whenever the state changes—even if they only need the dispatch function (which never changes). This creates performance waste.

The Split Pattern

Instead of one context with { state, dispatch }, create two:

const StateContext = createContext<MyState | undefined>(undefined);
const DispatchContext = createContext<Dispatch<MyAction> | undefined>(undefined);

Now your provider wraps with both:

function MyProvider({ children }: PropsWithChildren) {
  const [state, dispatch] = useReducer(myReducer, initialState);
  
  return (
    <StateContext.Provider value={state}>
      <DispatchContext.Provider value={dispatch}>
        {children}
      </DispatchContext.Provider>
    </StateContext.Provider>
  );
}

Components that only dispatch actions use useContext(DispatchContext)—they won't re-render when state changes because they're not subscribed to StateContext. Components that only read state use useContext(StateContext).

Why This Matters for TypeScript

Separate contexts = separate types. Your dispatch consumers get type safety without dragging in the full state type, making component dependencies explicit and reducing coupling.

The Analogy

Think of a restaurant: the kitchen (dispatch) doesn't need to know every diner's order status (state), and diners don't need access to the cooking equipment. Separate contexts = separate concerns.

Key Takeaway: Splitting state and dispatch into separate contexts prevents re-renders in components that only dispatch and makes TypeScript types cleaner and more focused.