Course contentsShow
← React
Lesson 852 of 2,39622. Context PerformanceFree lesson

Solution 2: Split Context into Separate Providers

Separate data and setters into different contexts so consumers only subscribe to what they need.

Solution 2: Split Context into Separate Providers

What you'll learn: How to eliminate unnecessary re-renders by separating data and setters into different contexts so components only subscribe to what they actually use.

The Core Idea

Instead of putting both state and its setter in one context value, create two separate contexts: one for the data, one for the updater function. Components that only need to trigger updates can subscribe to the updater context without re-rendering when the data changes.

Why This Works

Think of it like two radio frequencies: one broadcasting weather updates, one broadcasting the "request weather update" hotline number. If you only need to request updates, you tune into the hotline frequency—you don't need to hear every weather change.

When a component uses useContext, it subscribes to that entire context. If setUser lives in the same context as user, even components that only call setUser will re-render when user changes. Splitting them breaks this unnecessary subscription.

The Pattern

const UserContext = createContext<User | null>(null);
const UserUpdateContext = createContext<((user: User) => void) | null>(null);

function UserProvider({ children }) {
  const [user, setUser] = useState<User | null>(null);
  
  return (
    <UserContext.Provider value={user}>
      <UserUpdateContext.Provider value={setUser}>
        {children}
      </UserUpdateContext.Provider>
    </UserContext.Provider>
  );
}

Now components can choose: subscribe to UserContext (re-render on changes) or UserUpdateContext (never re-render, just update).

When to Use This

Perfect for forms, buttons, or actions that modify state but don't display it. The button that logs a user out doesn't need to re-render every time user data changes.

Key Takeaway: Splitting data and setters into separate contexts lets consumers opt into exactly the re-renders they need, eliminating wasted rendering for write-only components.