Sub topic 6
Nested providers and overriding values
This chapter assumes you can create a context, wrap a subtree in a Provider, and read the value with useContext. You should also know how a component's props and children work. Here you will see what happens when providers for the same context sit inside each other.
The nearest provider wins
useContext does not search the whole tree. It walks up from the component that calls it and returns the value of the closest matching provider above it. If you put a second provider for the same context inside the first, components below the second one see the new value. Components outside it still see the old one.
The nesting does not combine or merge values. The inner provider replaces the outer value for its own subtree and nothing else.
Example: automatic heading levels
A Section reads the current level and provides level + 1 to its children. A Heading reads the level and picks an h1 to h6 tag. No component passes a level as a prop.
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 Page() {
return (
<Section>
<Heading>Title</Heading>
<Section>
<Heading>Heading</Heading>
<Section>
<Heading>Sub-heading</Heading>
</Section>
</Section>
</Section>
);
}This renders an h1, an h2, and an h3. Two details explain the result:
- A component never sees the provider it renders itself.
SectioncallsuseContextand gets the value from above, then provides a new value only to its children. - A
Headingrendered outside everySectiongets the default value,0. TheMath.maxcall turns that intoh1instead of an invalid tag.
Overriding part of an object
Most real contexts hold objects. If an inner provider passes a partial object, the keys you leave out are gone, not inherited. To override only some fields, read the outer value and spread it.
import { createContext, useContext } from 'react';
const SettingsContext = createContext({ theme: 'light', compact: false });
function SettingsOverride({ changes, children }) {
const parent = useContext(SettingsContext);
return (
<SettingsContext.Provider value={{ ...parent, ...changes }}>
{children}
</SettingsContext.Provider>
);
}
function Panel({ title }) {
const { theme, compact } = useContext(SettingsContext);
return (
<div className={`panel-${theme}`}>
{title}: {compact ? 'compact' : 'roomy'}
</div>
);
}
export default function App() {
return (
<SettingsOverride changes={{ theme: 'dark' }}>
<Panel title="Outer" />
<SettingsOverride changes={{ compact: true }}>
<Panel title="Inner" />
</SettingsOverride>
</SettingsOverride>
);
}The outer panel sees { theme: 'dark', compact: false }. The inner panel sees { theme: 'dark', compact: true }. It keeps the dark theme because SettingsOverride copied it from parent.
Common errors
- Expecting a component to read its own provider. A provider affects only its descendants. If a component both provides and consumes the same context, it consumes the value from above.
- Overriding with a partial object. Spread the parent value as shown above.
- Different context objects. Two
createContextcalls make two separate contexts, even if they have the same default value. Nested providers override each other only when they come from the same context object. Importing from the wrong module is a common cause. - Creating a new object on every render.
{ ...parent, ...changes }creates a new object each timeSettingsOverriderenders, which re-renders every consumer below it. A later chapter covers memoizing the value.
Exercise
In the Page example, you add a Heading as a direct child of the outermost Section, after the second Section. Which tag does it render, and why?
Show answer
It renders an h1. The outermost Section provides level 1 to its direct children. The second Section's provider covers only that section's own subtree, so a sibling outside it still reads the value from the nearest provider above it.