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

Local Context for Component Subtrees

Discover how context can provide state to a specific subtree without polluting the global scope.

Local Context for Component Subtrees

What You'll Learn: How to scope context to just part of your component tree instead of making it globally available.

The Global Scope Problem

So far, you've seen context providers placed near the root of your app, making their values available everywhere. But context doesn't have to be global—you can create a provider anywhere in your component tree to share state with just that branch.

What is Local Context?

Local context means wrapping only a specific subtree of components with a provider, rather than your entire application. The context value is only accessible to descendants of that provider, not siblings or unrelated parts of your app.

Think of it like a private conversation in one room of a house—people in other rooms can't hear it, and that's exactly what you want.

Why Use Local Context?

  1. Isolation: State changes in one subtree don't risk affecting unrelated parts of your app
  2. Reusability: You can use the same context multiple times in different subtrees with different values
  3. Performance: Smaller context boundaries mean fewer components re-render when context changes
  4. Clarity: Makes it obvious which components have access to what data

Example Structure

Imagine a form wizard with multiple steps. Instead of putting form state in global context, create a provider just around the wizard:

<App>
  <Header />
  <FormWizardProvider>   ← Local provider
    <WizardStep1 />       ← Can access context
    <WizardStep2 />       ← Can access context
  </FormWizardProvider>
  <Footer />              ← Cannot access context
</App>

The Header and Footer remain isolated—they won't re-render when form state changes, and they can't accidentally consume or interfere with wizard state.

Key Takeaway: Context providers can wrap any subtree, not just your entire app—use local providers to keep state scoped, isolated, and performant.