The dark theme picked in the top corner has to reach a button placed five component layers below it. With props, all five layers have to pass theme along, even though not one of them uses it.
Context gives you a shortcut: a value from a component near the top can be read by any component below it, without passing it through props at every layer. Think of the announcement speaker in a school. Instead of the principal handing a message to the homeroom teacher, the teacher to the class captain, and the captain to every student, the principal speaks once over the speaker. Anyone listening hears it right away. When the announcement changes, every listener hears the new version. In React, the principal is the component near the top that holds the value, the speaker is the context, and the students who listen are the components that read the context.
The problem: prop drilling
The ThemedButton and Footer components need theme. The value is kept in App, and it has to pass through Layout and Toolbar in between:
function App() {
const [theme, setTheme] = useState("dark")
return <Layout theme={theme} />
}
function Layout({ theme }) {
return (
<div>
<Toolbar theme={theme} />
<Footer theme={theme} />
</div>
)
}
function Toolbar({ theme }) {
return (
<nav>
<ThemedButton theme={theme} />
</nav>
)
}
Layout and Toolbar don't use theme at all. They receive theme only to pass it down. Passing props through components that don't need them is called prop drilling. Two layers in between is fine. Ten layers means ten components to change every time there's new data.
Context in three steps
This is the same example, but using context. The numbers 1 to 3 in the code comments are the three steps:
import { createContext, useContext } from "react"
// 1. Make the context, with the default value "light"
const ThemeContext = createContext("light")
function App() {
// 2. The Provider supplies a value to every component inside it
return (
<ThemeContext.Provider value="dark">
<Layout />
</ThemeContext.Provider>
)
}
function Layout() {
return (
<div>
<Toolbar />
<Footer />
</div>
)
}
function Toolbar() {
return (
<nav>
<ThemedButton />
</nav>
)
}
function ThemedButton() {
// 3. Any component inside the Provider can read it
const theme = useContext(ThemeContext)
return <button className={theme}>Button {theme}</button>
}
function Footer() {
const theme = useContext(ThemeContext)
return <footer>Theme: {theme}</footer>
}
createContext("light")makes the context. Call it once, outside every component."light"is its default value.<ThemeContext.Provider value="dark">supplies the value"dark"to every component inside it, however deep. In React 19, you may also write the Provider as<ThemeContext value="dark">..Providerworks in every version, and it's what the exercise uses.const theme = useContext(ThemeContext)reads the value from the nearest Provider above, then{theme}shows it.LayoutandToolbarnow receive no props at all.
The result: a button reading Button dark, and a footer reading Theme: dark.
Forgot the Provider: the default value
You write createContext("light") but forget to add a Provider. Take a guess: does useContext(ThemeContext) give "light", undefined, or an error?
| Above the component | useContext(ThemeContext) gives |
|---|---|
<ThemeContext.Provider value="dark"> |
"dark" |
| No Provider at all | "light", the default from createContext |
Without a Provider there's no error. useContext quietly gives the default value, "light". So pick a default that makes sense. If the theme in your app won't change, first check that the component really sits inside the Provider.
The value changes: who renders again
Usually the Provider's value comes from state, and the Provider is placed in a component of its own, here ThemeProvider:
function ThemeProvider({ children }) {
const [theme, setTheme] = useState("dark")
const toggle = () => setTheme(theme === "dark" ? "light" : "dark")
return (
<ThemeContext.Provider value={theme}>
<button onClick={toggle}>Change theme</button>
{children}
</ThemeContext.Provider>
)
}
function App() {
return (
<ThemeProvider>
<Layout />
</ThemeProvider>
)
}
Click Change theme once, then count how many times each component has rendered (the first render counts too). The Prop drilling column is the version that passes theme through props:
| Component | Prop drilling | Context |
|---|---|---|
App |
2 | 1 |
ThemeProvider |
(none) | 2 |
Layout |
2 | 1 |
Toolbar |
2 | 1 |
ThemedButton |
2 | 2 |
Footer |
2 | 2 |
- When the Provider's
valuechanges, every component that callsuseContext(ThemeContext)renders again with the new value. This re-render can't be skipped. LayoutandToolbarstay at 1. OnlyThemeProviderholds the state, soAppdoesn't render again.<Layout />is made byAppand only passed on throughchildren, so React doesn't runLayoutagain.- If the state and the Provider are written straight in
Appnext to<Layout />,Layoutrenders again as usual, because its parent rendered again. With context you no longer pass the props, but the number of renders doesn't go down by itself.
In the example above, the Change theme button is inside ThemeProvider. To place the button anywhere, for example inside Toolbar, share toggle through the context too:
const ThemeContext = createContext(null)
function ThemeProvider({ children }) {
const [theme, setTheme] = useState("dark")
const toggle = () => setTheme(theme === "dark" ? "light" : "dark")
return (
<ThemeContext.Provider value={{ theme, toggle }}>
{children}
</ThemeContext.Provider>
)
}
function ThemeToggle() {
const { theme, toggle } = useContext(ThemeContext)
return <button onClick={toggle}>Theme: {theme}</button>
}
valueis now the object{ theme, toggle }, so each reader (a component that callsuseContext) takes the part it needs:const { theme } = useContext(ThemeContext).- Put
<ThemeToggle />insideToolbar. Click it once, and the text changes fromTheme: darktoTheme: light. - The object
{ theme, toggle }is made new every timeThemeProviderrenders, even whenthemedid not change. Because the object is new, every reader renders again. Wrap that object inuseMemo(from the useMemo and useCallback lesson) so that a new object is made only whenthemechanges.
🎯 Context or props?
- Global data that rarely changes (used in many places: theme, language, the logged-in user): Context.
- Data for a direct child or two layers down: plain props, because it's clearer where the data comes from.
- State only one component uses (a dropdown open or closed):
useStatein that component.
⚠️ When the context value doesn't arrive
- Forgetting the Provider. No error, only the default value appears. Check where the component sits: it has to be inside the Provider.
- Typing the value in directly. In the exercise,
<p id="theme">dark</p>looks right, but it doesn't read the context. Store it in a variable first,const theme = useContext(ThemeContext), then show{theme}. - Destructuring a value that isn't an object. The value is the string
"dark", soconst { theme } = useContext(ThemeContext)givesundefined. Destructuring is only for a value that is an object. - A Provider with no
value.<ThemeContext.Provider>withoutvaluesuppliesundefined, not the default value.
TL;DR: Context solves prop drilling, which is passing props through components that don't need them. There are three steps. First, write const ThemeContext = createContext("light") outside every component. Second, wrap the components that need the value in <ThemeContext.Provider value="dark">. Third, read the value in any component inside with const theme = useContext(ThemeContext), then show {theme}. Without a Provider, useContext gives the default value ("light") with no error. When value changes, every component that calls useContext renders again. Use Context for global data (used in many places) that rarely changes. When the data only goes one or two component layers down, plain props are enough.
⚡ The problem: prop drilling
Meaning: Say the value theme (a dark or light theme) is kept in App, but the ones that need it are ThemedButton and Footer, further down. Layout and Toolbar sit in between, and receive theme only to pass it down. Passing props through components that don't need them is called prop drilling.
⚡ Context in three steps
Write:
// 1. Make the context, with the default value "light"
const ThemeContext = createContext("light")
function App() {
// 2. The Provider supplies a value to every component inside it
return (
<ThemeContext.Provider value="dark">
<Layout />
</ThemeContext.Provider>
)
}
function ThemedButton() {
// 3. Any component inside the Provider can read it
const theme = useContext(ThemeContext)
return <button className={theme}>Button {theme}</button>
}
Meaning: Context lets any component below read a value from a component above, without props. Step 1: createContext("light") is written outside the components, and "light" is its default value. Step 2: the Provider wraps the components below it and supplies the value "dark". Step 3: useContext(ThemeContext) reads that value. Layout and Toolbar don't need to receive theme any more.
⚡ Forgot the Provider
Guess first: the context is made with createContext("light"), but you forgot to add a Provider. Does useContext(ThemeContext) give "light", undefined, or an error?
"light", the default from createContext("light"). There's no error, so pick a default that makes sense.
Meaning: One more thing about the Provider: once the Provider's value changes, every component that calls useContext(ThemeContext) renders again with the new value.