Sub topic 13
Prop drilling and when to use context
This chapter assumes you can pass props, use the children prop and callback props, and call useState. It covers what to do when a value has to travel through many components.
What prop drilling is
Prop drilling means passing a prop through components that don't use it, only so a deeper component can receive it. Here user starts in App and is needed only in UserBadge.
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>{user.name}</p>;
}Is drilling a problem?
Not by itself. Passing a prop through two or three levels is explicit, easy to trace, and easy to search for. Drilling becomes costly in these cases:
- The value passes through many layers.
- Several values travel the same path.
- Changing the shape of the value means editing every component on the path.
- Middle components accept props they never use, which makes them harder to reuse.
Fix 1: restructure with composition
Before you reach for context, check whether the middle components need to know about the data at all. If App builds the element and passes it down as a slot, Page and Sidebar stop handling user.
function App() {
const user = { name: 'Ada' };
return <Page sidebar={<UserBadge user={user} />} />;
}
function Page({ sidebar }) {
return <aside>{sidebar}</aside>;
}
function UserBadge({ user }) {
return <p>{user.name}</p>;
}This keeps data flow explicit and often removes the problem completely.
Fix 2: context
Context lets a component make a value available to everything below it, with no props in between. There are three steps:
- Create the context with
createContext(defaultValue). - Wrap a subtree in
Context.Providerand set itsvalue. - Read the value in any descendant with
useContext(Context).
import { createContext, useContext, useState } from 'react';
const ThemeContext = createContext('light');
function ThemedLabel() {
const theme = useContext(ThemeContext);
return <p className={theme}>Current theme: {theme}</p>;
}
function Toolbar() {
return <ThemedLabel />;
}
function Page() {
return <Toolbar />;
}
export default function App() {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={theme}>
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Toggle theme
</button>
<Page />
</ThemeContext.Provider>
);
}Page and Toolbar take no props. ThemedLabel reads the theme directly, and it re-renders when the provider's value changes.
Trade-offs of context
- Hidden dependencies. A component that calls
useContextworks only under the right provider. Its inputs are no longer visible in its signature. - Default value. The argument to
createContextis used only when no provider sits above the component. - Re-rendering. Every consumer re-renders when the provider's
valuechanges. If you writevalue={{ user, theme }}, a new object is created on each render of the provider, so every consumer re-renders each time. Keep the value stable, or split unrelated data into separate contexts. memodoes not help consumers. A memoized component still re-renders when a context it reads changes.
Choosing an approach
| Situation | Prefer |
|---|---|
| Value passes through one or two levels | Plain props |
| Middle components only forward the value | Composition with `children` or slot props |
| Many distant components need the same value | Context |
| Data changes often and many components read it | Split contexts, or a state library |
Exercise
A Layout component receives a currentUser prop only to pass it to Header, which passes it to Avatar. Name two ways to remove the forwarding, and say when you would pick each.
Show answer
First, composition: build <Avatar user={currentUser} /> in the component that owns the data and pass it to Layout as a slot prop such as header, or as children. Pick this when the middle components don't need to know about the data. Second, context: provide currentUser with a Provider high in the tree and call useContext in Avatar. Pick this when many components at different depths need the value and it changes rarely.