Sub topic 3
Providing a value to a subtree
This chapter assumes you know JavaScript ES6 syntax, React function components, JSX, props, and the useState hook. You should also know the basic idea that React re-renders a component when its state or props change. Earlier chapters introduced the prop drilling problem and createContext. Here you will learn how a Provider decides which components can see a value.
What a Provider does
A context object created by createContext holds nothing on its own. It is a channel. A Provider puts a value into that channel for a specific part of the component tree.
Every context object has a Provider component. You render it like any other component and give it a value prop:
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>Every component rendered inside the Provider, at any depth, can read "dark" with useContext(ThemeContext). That group of components is the Provider's subtree. Components outside the subtree do not see this value.
Two points are easy to miss:
- The Provider does not render any DOM element. It only supplies a value, so it does not change your HTML or your layout.
- The
valueprop is required in practice. If you leave it out, consumers receiveundefined. They do not receive the default value fromcreateContext. The default is used only when there is no Provider above the consumer at all.
A complete example
The example below creates a context, supplies a changing value from App, and reads it deep in the tree. Toolbar passes no props to ThemedButton.
import { createContext, useContext, useState } from 'react';
const ThemeContext = createContext('light');
function App() {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={theme}>
<Toolbar />
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Toggle theme
</button>
</ThemeContext.Provider>
);
}
function Toolbar() {
return <ThemedButton />;
}
function ThemedButton() {
const theme = useContext(ThemeContext);
return <button className={`btn-${theme}`}>Save</button>;
}Follow the data through the code:
Appholdsthemein state and passes it to the Provider'svalueprop.ToolbarrendersThemedButtonand knows nothing about the theme.ThemedButtoncallsuseContext(ThemeContext). React walks up the tree fromThemedButtonand returns the value of the nearestThemeContext.Provider.- When you click the toggle button,
Appupdates its state and re-renders. The Provider receives a newvalue, and React re-rendersThemedButtonwith it.
Notice that the toggle button is also inside the Provider, but it does not read the context. It only needs theme for its own click handler, and it gets that from App's own scope.
How the subtree is determined
The subtree is defined by where the Provider appears in the JSX tree, not by where the context object was created or imported. This diagram shows which components can read the value.
If Footer called useContext(ThemeContext), it would get the default value from createContext('light'), because no Provider sits above it.
What counts as "inside"
A component is inside the subtree if the Provider is one of its ancestors in the rendered tree. In practice this usually means the component is written between the Provider's opening and closing tags, or is rendered by something that is.
Components passed as children are a common case. In this example, Page is rendered inside the Provider because AppShell places children there:
import { createContext, useContext } from 'react';
const UserContext = createContext('guest');
function AppShell({ children }) {
return (
<UserContext.Provider value="Dana">
{children}
</UserContext.Provider>
);
}
function Page() {
const user = useContext(UserContext);
return <p>Signed in as {user}</p>;
}
export default function Root() {
return (
<AppShell>
<Page />
</AppShell>
);
}Page is written in Root, but it is rendered as a descendant of the Provider. It prints Signed in as Dana. What matters is the position in the rendered tree, not which file or function wrote the JSX.
Placing the Provider
Put the Provider as low in the tree as possible while still wrapping every component that needs the value. Two common choices:
- Near the root. Use this for values that the whole app needs, such as the current user or theme. This is the usual place for a theme or authentication Provider.
- Around one feature. Use this for values that only one section needs, such as the state of a multi-step form. A narrow Provider keeps the value out of unrelated components and makes it easier to see who depends on it.
A Provider can also be rendered more than once. Each copy supplies its own value to its own subtree. Two siblings with different Providers do not affect each other.
<>
<ThemeContext.Provider value="light">
<Sidebar />
</ThemeContext.Provider>
<ThemeContext.Provider value="dark">
<MainPanel />
</ThemeContext.Provider>
</>Sidebar and everything in it see "light". MainPanel and everything in it see "dark". The next chapters cover what happens when Providers are nested inside each other.
The value is compared by identity
React decides whether a Provider's value changed by comparing the old and new value with Object.is. For strings and numbers this behaves as you expect: "dark" is the same as "dark".
For objects, arrays, and functions, a new copy is a different value even if its contents are identical. This matters when you write:
<ThemeContext.Provider value={{ theme, toggle }}>The expression { theme, toggle } creates a new object every time this component renders. React sees a different value on every render, so every consumer re-renders each time the parent renders, even if theme and toggle did not change. For a small app this is harmless. In a large tree it can cause needless work. A later chapter covers how to avoid it with useMemo.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Consumer shows the default value | No Provider above the consumer, or the Provider wraps a different branch of the tree | Move the Provider so it is an ancestor of the consumer |
| Consumer gets `undefined` | The Provider has no `value` prop | Pass `value` explicitly |
| Consumer shows the wrong value | A different Provider for the same context sits closer to it | Check for a nested Provider and remove it or use it deliberately |
| Value never updates | The Provider was given a constant, or state was changed without calling its setter | Pass state from `useState` and update it with the setter |
| `Cannot read properties of null` | The default was `null` and the consumer ran without a Provider | Add the Provider, or throw a clear error in a custom hook |
| Provider is not found even though you wrote one | You imported a different context object, for example from a duplicated file | Export one context from one module and import it everywhere |
The last row is worth remembering. Context identity is the object itself. Two calls to createContext give two unrelated contexts, even if they have the same name and default. A Provider only reaches consumers that use the same object.
This warning matches a frequent mistake. Consider this component:
function Panel() {
const theme = useContext(ThemeContext); // reads from above Panel
return (
<ThemeContext.Provider value="dark">
<Child /> {/* Child sees "dark", Panel does not */}
</ThemeContext.Provider>
);
}Panel reads whatever Provider is above it, or the default if there is none. Only Child and its descendants see "dark".
Summary
- A Provider supplies a value to every component in its subtree, at any depth.
- The subtree is the set of components rendered beneath the Provider in the tree.
useContextreturns the value of the nearest Provider above the calling component.- The default value from
createContextis used only when no Provider is above the consumer. - Omitting
valuegives consumersundefined, not the default. - React compares values with
Object.is, so a new object on each render counts as a change.
Exercise
In this code, what does each of A, B, and C read, given const LangContext = createContext('en');?
<LangContext.Provider value="fr">
<A />
</LangContext.Provider>
<B />
<LangContext.Provider>
<C />
</LangContext.Provider>
(Assume each of A, B, and C calls useContext(LangContext).)
Show answer
A reads "fr", because it is inside a Provider with that value. B reads "en", the default, because no Provider is above it. C reads undefined, because its Provider has no value prop, and the default is used only when there is no Provider at all.
Exercise
A component renders <ThemeContext.Provider value={{ theme, toggle }}>. The theme and toggle values have not changed, yet all consumers re-render whenever the parent re-renders. Why?
Show answer
The object literal { theme, toggle } is a new object on every render. React compares the value with Object.is, finds a different object, and re-renders all consumers. Memoizing the object with useMemo keeps the same identity until theme or toggle changes.