Sub topic 13
Prop drilling and when to use context
What this chapter assumes
You should already know how to pass props, destructure them, pass functions as callback props, and use children. You should also know that state lives in a component and that a parent owns the state it passes down. This chapter covers what happens when data must travel through many layers. It also covers the three ways to handle that: keep drilling, restructure with composition, or use context.
What prop drilling is
Prop drilling means passing a prop through components that do not use it, only so that a deeper component can receive it. Each intermediate component acts as a relay.
function App() {
const user = { name: 'Ada' };
return <Page user={user} />;
}
function Page({ user }) {
return <Sidebar user={user} />;
}
function Sidebar({ user }) {
return <UserBadge user={user} />;
}
function UserBadge({ user }) {
return <p>Signed in as {user.name}</p>;
}Only UserBadge reads user. Page and Sidebar accept it and forward it. The data flows in one direction, from parent to child, so the path is easy to trace. The cost is in the middle layers.
When drilling is a problem
Drilling is not a bug. Two or three levels of explicit props are often the clearest code you can write. It becomes a problem in these cases:
- Renames and shape changes. If
userbecomescurrentUser, you edit every component in the chain. - Unrelated components know about the data.
Sidebarnow has auserprop even though it has nothing to do with users. Its type, its tests, and its stories all carry that prop. - Many consumers at many depths. If ten components at different depths need the same value, the intermediate components collect a long list of props they only forward.
- Props that rarely change but are needed everywhere. Examples are the theme, locale, and signed-in user.
If none of these apply, keep drilling. It is the most explicit option, and tools can trace every use of a prop.
First alternative: composition
Before you reach for context, check whether the structure is the issue. Often a parent can build the deep element itself and pass it down as children or a slot prop. The middle components then never see the data.
function App() {
const user = { name: 'Ada' };
return <Page sidebar={<UserBadge user={user} />} />;
}
function Page({ sidebar }) {
return (
<div>
<aside>{sidebar}</aside>
<main>Main content</main>
</div>
);
}
function UserBadge({ user }) {
return <p>Signed in as {user.name}</p>;
}App creates the <UserBadge> element and gives it user directly. Page renders whatever it receives in the sidebar slot. The prop path went from three hops to zero, and Page became more reusable.
Composition has limits. It moves logic upward, so the top components get more complex. If many unrelated parts of the tree need the same value, passing prebuilt elements through every layout does not scale.
Context: reading a value without passing it
Context lets a component provide a value to everything below it in the tree. Any descendant can read that value, at any depth, with no props in between. There are three parts:
createContext(defaultValue)creates the context object.- A
Providercomponent wraps part of the tree and supplies the value. useContext(TheContext)reads the nearest provider's value in a descendant.
The example below shares a theme and a function to change it. Put the context, provider, and a custom hook in one place, so consumers never touch the raw context object.
import { createContext, useContext, useMemo, useState } from 'react';
const ThemeContext = createContext(null);
export function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
const value = useMemo(() => ({ theme, setTheme }), [theme]);
return (
<ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>
);
}
export function useTheme() {
const ctx = useContext(ThemeContext);
if (ctx === null) {
throw new Error('useTheme must be used inside a ThemeProvider');
}
return ctx;
}
function ThemeToggle() {
const { theme, setTheme } = useTheme();
return (
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Theme: {theme}
</button>
);
}
function Toolbar() {
return (
<nav>
<ThemeToggle />
</nav>
);
}
function Page() {
return <Toolbar />;
}
export default function App() {
return (
<ThemeProvider>
<Page />
</ThemeProvider>
);
}Page and Toolbar take no props. ThemeToggle reads the context and also calls setTheme. The state still lives in ThemeProvider, and the context only delivers it.
The provider receives children, so App creates <Page />. When ThemeProvider updates its state, React does not re-render Page just because the provider re-rendered. Only components that call useTheme re-render. This is the children-prop pattern from earlier in the tutorial at work.
React 19 also accepts <ThemeContext value={value}> without .Provider. The .Provider form works in every React version.
How context and re-rendering interact
When a provider's value changes, React re-renders every component that reads that context. The comparison uses Object.is, so a new object each render counts as a change.
This is why the example wraps the value in useMemo. Without it, { theme, setTheme } is a new object each time ThemeProvider renders, and every consumer re-renders, even if theme did not change. In this small example that does not matter, but in a large tree it can.
There are two consequences:
- A consumer cannot subscribe to part of a context value. A component that only reads
setThemestill re-renders whenthemechanges, because the whole value object changed. - A
memowrapper does not stop a context update.memocompares props, and context changes bypass props.
To limit this, split contexts by how often they change. A common pattern is one context for the state and another for the update function. You can also keep fast-changing values, such as input text or mouse position, out of context.
Common errors
Reading context outside a provider. If you create the context with createContext(null) and no provider is above the consumer, useContext returns null. Destructuring it then throws a confusing Cannot destructure property error. The useTheme hook above fails with a clear message instead.
A new object on every render. Writing value={{ theme, setTheme }} inline causes the consumer re-renders described above. Memoize the value when the provider re-renders often or has many consumers.
Putting everything in one context. A single AppContext holding user, theme, cart, and notifications makes every consumer re-render on every change. Use several small contexts.
Using context to avoid two levels of props. Context hides the data flow. A reader of ThemeToggle can no longer see in the parent's JSX where the theme came from. Reserve it for values that many components need.
Mutating the context value. The read-only rule applies here as well. Consumers should never change ctx.user.name directly. Expose update functions from the provider instead, as setTheme does.
Choosing between the options
| Situation | Best fit |
|---|---|
| One or two levels, one or two consumers | Plain props |
| A layout wraps content that needs parent data | Composition with `children` or slot props |
| Many components at many depths read the same value | Context |
| The value is global and changes rarely (theme, locale, signed-in user) | Context |
| The value changes many times per second | Props, or an external store with selective subscriptions |
| You want a reusable component with an explicit, testable interface | Props |
The reusability point matters. A component that reads context has a hidden dependency. It only works inside a matching provider. A component that takes props can be rendered anywhere, including in a test with no setup. For a component you plan to reuse widely, prefer props for its core inputs. You can still supply them from context in a thin wrapper.
Exercise
A Dashboard component renders Header, which renders Menu, which renders UserAvatar. Only UserAvatar needs the user object, and Dashboard owns it. Name two ways to avoid passing user through Header and Menu. Then say which one you would choose if 15 components at different depths also needed user, and why.
Show answer
Option one is composition. Dashboard builds <UserAvatar user={user} /> and passes it into Header as a slot prop or as children, so Header and Menu never see user. Option two is context. A UserProvider supplies user, and UserAvatar calls useUser(). With 15 consumers at different depths, I would choose context, because composition would require threading prebuilt elements through many layouts. I would memoize the provider's value and keep any rarely used setters in a separate context so consumers do not re-render needlessly.