Course contentsShow
← React
Lesson 2255 of 2,39649. Performance: Identifying ProblemsFree lesson

The Read vs Write Context Split Pattern

Separating state values and update functions into different contexts so components only subscribe to what they need.

The Read vs Write Context Split Pattern

What you'll learn: How to split a single context into separate read and write contexts so components only re-render when the data changes, not when updater functions change.

The Core Problem This Solves

When you provide both state values and update functions in a single context object, every consumer re-renders whenever the context value changes — even if a component only uses the updater functions and doesn't care about the state itself.

This happens because React compares context values by reference. When you create value={{ count, setCount }} on every render, it's a new object every time, triggering all consumers.

The Split Pattern

Instead of one context:

const AppContext = createContext();

function AppProvider({ children }) {
  const [count, setCount] = useState(0);
  return (
    <AppContext.Provider value={{ count, setCount }}>
      {children}
    </AppContext.Provider>
  );
}

Split it into two contexts:

const CountReadContext = createContext();
const CountWriteContext = createContext();

function AppProvider({ children }) {
  const [count, setCount] = useState(0);
  return (
    <CountReadContext.Provider value={count}>
      <CountWriteContext.Provider value={setCount}>
        {children}
      </CountWriteContext.Provider>
    </CountReadContext.Provider>
  );
}

Now components that only increment the counter can consume CountWriteContext — they'll never re-render when count changes, because setCount is a stable reference. Components displaying the count consume CountReadContext and only re-render when the actual value updates.

The Analogy

Think of a library: some people only read books (they care when new books arrive), while others only write checkout slips (they don't care what's on the shelves). If you announce every event to everyone, the writers get interrupted unnecessarily.

Key Takeaway: Separate state values and updater functions into distinct contexts so components can subscribe to exactly what they need — preventing unnecessary re-renders for components that only dispatch actions.