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

Co-locating Context with Its Consumers

Placing context providers close to the subtree that uses them to limit re-render scope.

Co-locating Context with Its Consumers

What you'll learn: How placing context providers close to the components that actually use them limits unnecessary re-renders across your app.

The Location Problem

When you create a context provider, where you place it in your component tree matters enormously for performance. Many developers instinctively wrap their entire app at the root level with every provider they create. This means every component becomes a potential victim of re-renders when that context changes—even components that never consume it.

The Co-location Strategy

Co-location means placing your context provider as close as possible to the subtree that actually needs it. Instead of wrapping your entire <App> component, wrap only the branch of components that consume that context.

Why This Works

Think of context providers like electrical circuits in a house. You could run every light and appliance through one giant circuit breaker at the main panel—but when that breaker trips, the entire house goes dark. Better to have separate circuits for different rooms. When the kitchen circuit trips, your bedroom lights stay on.

Similarly, a provider at the root level means context changes can trigger re-renders throughout your entire component tree. A provider wrapped around just a <Dashboard> component limits the blast radius to that subtree only.

Practical Example

Instead of this structure:

<App>
  <ThemeProvider>
    <UserProvider>
      <Sidebar /> {/* doesn't need user */}
      <Dashboard /> {/* needs user */}
    </UserProvider>
  </ThemeProvider>
</App>

Do this:

<App>
  <ThemeProvider>
    <Sidebar />
    <UserProvider>
      <Dashboard />
    </UserProvider>
  </ThemeProvider>
</App>

Now when user context changes, <Sidebar> never re-renders.

Key Takeaway: Place context providers as close to their consumers as possible—this limits re-render scope to only the subtree that actually depends on that context, dramatically improving performance in large applications.