Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Routing and Application Architecture
Stage 5: Specialization (pick ONE)

Part 09 / Topic 5 of 6

Splitting contexts to limit unnecessary re-renders

Every component that calls useContext(SomeContext) re-renders whenever that Provider's value changes - React has no way to know a specific consumer only reads part of that value. Bundling unrelated state into one context value means a change to any one piece re-renders every consumer of the whole thing. examples/05_splitting_contexts_for_rerenders.jsx proves the cost with a render counter, the same technique Part 6 used:

// examples/05_splitting_contexts_for_rerenders.jsx - combined
return (
  <AppContextCombined.Provider value={{ theme, toggleTheme, user }}>{children}</AppContextCombined.Provider>
);

Toggling the theme on AppCombined really bumps both ThemeDisplayCombined's and UserDisplayCombined's render counts on every click, even though user never changes (examples/05_splitting_contexts_for_rerenders.test.jsx) - UserDisplayCombined only reads user, but it reads it off the same context object that just got a brand-new { theme, toggleTheme, user } value, so React has no choice but to re-render it too. AppSplit puts theme/toggleTheme in one context and user in a separate one:

// examples/05_splitting_contexts_for_rerenders.jsx - split
<UserContextSplit.Provider value={user}>
  <ThemeContextSplit.Provider value={{ theme, toggleTheme }}>{children}</ThemeContextSplit.Provider>
</UserContextSplit.Provider>

The exact same theme toggle on AppSplit really leaves UserDisplaySplit's render count untouched the entire time - still 1 after two theme toggles - while ThemeDisplaySplit's climbs normally. The one detail that makes this actually work: value={user} passes the same object useState already holds, not a freshly-built { user } wrapper - wrapping it in a new object literal on every render of the Provider would change that context's value identity on every render too, silently defeating the split (see Common mistakes, below).

๐Ÿ” Going deeper: this performance ceiling - not "context is slow," specifically "every consumer re-renders on any change to its context's value" - is this course's answer to "is context a general state-management replacement?" (this part's stated learning outcome). It is not: a real app with many independently-changing pieces of global state either splits contexts aggressively (as above) or reaches for a reducer (Part 10) or a dedicated library (Stage 5) once that becomes unwieldy.

Done here? The practice set for Part 9 โ€” including the solutions โ€” is on the part page.

Search the guide