Course contentsShow
← React
Lesson 792 of 2,39621. Context FundamentalsFree lesson

Provider Placement in the Component Tree

Deciding where to place Providers based on which components need access to the context value.

Provider Placement in the Component Tree

What you'll learn: How to decide where in your component hierarchy to place a Context Provider so the right components can access its value.

The Golden Rule: Place at the Lowest Common Ancestor

When you wrap components with a Provider, only that Provider's descendants (children, grandchildren, etc.) can access the context value. Components outside or above the Provider cannot consume it.

The key decision: Where do you place the Provider?

Think Like a Network Engineer

Imagine context as a Wi-Fi router. You wouldn't install it in the basement if only the second floor needs internet, and you wouldn't put it on the roof if the whole house needs coverage. You place it strategically so everything that needs access can reach it—without covering areas that don't need it.

Practical Placement Strategy

1. Too High (App Root):

<ThemeContext.Provider value={theme}>
  <App />  {/* Everything can access theme */}
</ThemeContext.Provider>

Works, but may be overkill if only part of your app needs theming.

2. Just Right (Section Root):

<App>
  <Header />
  <ThemeContext.Provider value={theme}>
    <MainContent />  {/* Only this branch gets theme */}
  </ThemeContext.Provider>
</App>

Header can't access theme—which might be exactly what you want!

3. Too Low:

<div>
  <ThemeContext.Provider value={theme}>
    <Button />
  </ThemeContext.Provider>
  <AnotherButton />  {/* Can't access theme! */}
</div>

AnotherButton is left out—probably not intended.

Choosing Wisely

Ask yourself: "What's the smallest subtree that includes all components needing this context?" Place the Provider there. This keeps your context scope focused and avoids unnecessary re-renders in unrelated parts of your app.

Key Takeaway: Place your Provider at the lowest common ancestor of all components that need the context—high enough to cover everything that needs it, but no higher.