Sub topic 6
Nested providers and overriding values
This chapter assumes you can write React function components, use useState, and have already created a context, supplied a value with a Provider, and read it with useContext. Here you will learn how React picks a value when several Providers of the same context are stacked, and how to use that to build components that adapt to where they sit in the tree.
The nearest provider wins
A context can have more than one Provider in the same tree. When a component calls useContext(SomeContext), React looks upward from that component and returns the value of the closest SomeContext.Provider it finds. Providers further up are ignored for that component.
If no Provider of that context exists above the component, React returns the default value passed to createContext. The default is the last fallback, not a value that sits "under" the others.
Consider this tree:
<ThemeContext.Provider value="light">
<Page />
<ThemeContext.Provider value="dark">
<Sidebar />
</ThemeContext.Provider>
</ThemeContext.Provider>Page reads "light". Sidebar reads "dark", because the inner Provider is closer. The inner Provider affects only its own subtree. Nothing outside it changes.
Overriding a value for one subtree
Overriding is useful when one region of the UI needs different settings from the rest. Common cases:
- A dark panel inside a light page.
- A form section that is disabled while the rest of the page stays active.
- A modal that needs a different layout density.
Here is a complete example. The page is light, and a footer is forced to dark.
import { createContext, useContext } from 'react';
const ThemeContext = createContext('light');
function Label({ children }) {
const theme = useContext(ThemeContext);
return <p className={`label-${theme}`}>{children}</p>;
}
function Footer() {
return (
<ThemeContext.Provider value="dark">
<Label>Footer text</Label>
</ThemeContext.Provider>
);
}
export default function App() {
return (
<ThemeContext.Provider value="light">
<Label>Page text</Label>
<Footer />
</ThemeContext.Provider>
);
}Label has no props for the theme and does not know it is being overridden. It reads whatever value is closest. The override lives in Footer, so any component placed inside Footer follows it.
Deriving the value from the parent
An inner Provider can compute its value from the one above it. To do that, the component that renders the inner Provider calls useContext on the same context first, then passes a new value down. This is the pattern behind the Section and Heading components from the topic's heading-level example.
import { createContext, useContext } from 'react';
const LevelContext = createContext(0);
function Section({ children }) {
const level = useContext(LevelContext);
return (
<section>
<LevelContext.Provider value={level + 1}>{children}</LevelContext.Provider>
</section>
);
}
function Heading({ children }) {
const level = useContext(LevelContext);
const Tag = `h${Math.min(Math.max(level, 1), 6)}`;
return <Tag>{children}</Tag>;
}
export default function Article() {
return (
<Section>
<Heading>Title</Heading>
<Section>
<Heading>Subtitle</Heading>
<Section>
<Heading>Sub-subtitle</Heading>
</Section>
</Section>
</Section>
);
}Trace the values:
| Component | Providers above it | Value read | Rendered tag |
|---|---|---|---|
| Heading "Title" | 1 Section | 1 | `h1` |
| Heading "Subtitle" | 2 Sections | 2 | `h2` |
| Heading "Sub-subtitle" | 3 Sections | 3 | `h3` |
The outermost Section reads the default, 0, because no Provider is above it. It then provides 1. Each nested Section reads the value from the Provider above it and adds one. The Math.min(Math.max(level, 1), 6) call keeps the tag between h1 and h6. It also covers a Heading placed outside any Section, where level is 0.
Different contexts do not interfere
Nesting only matters for Providers of the same context object. Two different contexts, each with its own Provider, are independent. You can stack as many as you need, in any order.
<ThemeContext.Provider value="dark">
<LocaleContext.Provider value="fr">
<Page />
</LocaleContext.Provider>
</ThemeContext.Provider>Page and everything below it can read both. Overriding ThemeContext further down has no effect on LocaleContext.
A context is identified by the object that createContext returned. If you accidentally create the same context twice, for example by calling createContext inside a component or in two files, the two objects are unrelated. A Provider from one is invisible to consumers of the other, and consumers fall back to the default.
Common mistakes
Expecting an override to reach outside its subtree
An inner Provider changes values only for its descendants. A sibling or parent never sees it. If a component outside the Provider needs the new value, the value must be lifted to a place above both.
Providers wrapped around the wrong children
A frequent bug is placing a Provider next to a component instead of around it:
// Wrong: Panel is a sibling, not a child
<ThemeContext.Provider value="dark" />
<Panel />
// Right
<ThemeContext.Provider value="dark">
<Panel />
</ThemeContext.Provider>In the first version the Provider has no children, so Panel reads whatever is above, or the default.
Importing the wrong context
When a project defines several contexts with similar names, a consumer can import the wrong one. It then silently returns a default value. If a component always shows the default, check that the import path matches the one used by the Provider.
Forgetting that the default hides missing providers
With createContext('light'), a consumer outside every Provider reads 'light' and no error appears. This can hide a misplaced Provider. A later chapter covers a custom hook that throws when the Provider is missing. For now, if an override seems ignored, confirm that the consumer really is inside the Provider you expect.
Re-renders and nested Providers
When the value of a Provider changes, React re-renders the consumers that read from that Provider. With nesting, only consumers whose nearest Provider changed are affected. In the earlier example, if the outer value changes from "light" to "blue", Page updates. Sidebar does not, because its nearest Provider still supplies "dark".
This gives you a way to limit updates: place a stable inner Provider around a region that should not follow changes from above. Use it with care, because it also cuts that region off from the outer value on purpose.
Putting it together
The following example combines state, a toggle, and a nested override. The inner panel always stays dark. The rest of the page follows the toggle.
import { createContext, useContext, useState } from 'react';
const ThemeContext = createContext('light');
function Box({ name }) {
const theme = useContext(ThemeContext);
return <div className={`box-${theme}`}>{name}: {theme}</div>;
}
function DarkPanel({ children }) {
return <ThemeContext.Provider value="dark">{children}</ThemeContext.Provider>;
}
export default function App() {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={theme}>
<Box name="Header" />
<DarkPanel>
<Box name="Panel" />
</DarkPanel>
<button onClick={() => setTheme(theme === 'light' ? 'blue' : 'light')}>
Change page theme
</button>
</ThemeContext.Provider>
);
}Clicking the button switches Header between light and blue. Panel stays dark at every step, because DarkPanel supplies its own value.
Exercise
In the tree below, what value does each Reader read? Reader A, B and C are all components that call useContext(NumContext), and NumContext was created with createContext(0). <Reader name="A" /> <NumContext.Provider value={1}> <Reader name="B" /> <NumContext.Provider value={2}> <Reader name="C" /> </NumContext.Provider> </NumContext.Provider>
Show answer
A reads 0, the default, because no Provider is above it. B reads 1, from the nearest Provider above it. C reads 2, because the inner Provider is closer than the outer one.
Exercise
A Section component calls useContext(LevelContext) and then renders LevelContext.Provider with value={level + 1}. The tree has no Provider above the first Section, and LevelContext was created with createContext(0). What does a Heading read when it is placed two Sections deep?
Show answer
It reads 2. The first Section reads the default 0 and provides 1. The second Section reads 1 and provides 2. The Heading reads the nearest Provider, which supplies 2.