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

Setting Up a Provider Component

Wrapping part of your component tree with Context.Provider to make values available to descendants.

Setting Up a Provider Component

What you'll learn: How to wrap part of your component tree with Context.Provider to share values with descendant components.

The Core Idea

Once you've created a Context object with createContext, the next step is actually using it. The Context object has a .Provider component that acts as the "broadcaster" — it wraps a portion of your component tree and makes a value available to all components nested inside it, no matter how deep.

Think of it like a radio tower: you place the tower (Provider) somewhere in your app, set what it broadcasts (the value), and any component with a receiver inside its coverage area can tune in.

Basic Pattern

import { createContext } from 'react';

const ThemeContext = createContext('light');

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <Toolbar />
      <MainContent />
    </ThemeContext.Provider>
  );
}

The Provider component accepts a value prop — this is what gets shared. Any component inside <Toolbar /> or <MainContent /> (and their children, grandchildren, etc.) can now access "dark".

Where to Place the Provider

You control the "zone" of availability by where you place the Provider. Wrap your entire app to make it global, or wrap just a section to limit scope:

function Dashboard() {
  return (
    <UserContext.Provider value={currentUser}>
      <Sidebar />
      <Feed />
    </UserContext.Provider>
  );
}

Components outside <Dashboard /> won't have access to this context.

Key Takeaway: The Provider component wraps part of your tree and broadcasts a value to all descendants — placement determines scope, and the value prop determines what gets shared.