Sub topic 1
The problem: passing props through many layers
React passes data down the component tree through props. That works well until a value is needed far from where it lives. Then every component in between has to carry the value even though it never uses it. This chapter describes that problem, which is usually called prop drilling. It shows how to recognize it in code and when it is harmless. It also lists the options you have before you reach for context.
Prerequisites
This chapter assumes you already know:
- JavaScript ES6 syntax: destructuring, arrow functions and modules.
- React function components, JSX and props.
- The
useStatehook. - The basics of how React re-renders a component when its state or props change.
You do not need to know anything about context yet. Learning why it exists comes first.
What prop drilling is
React data flows one way. A parent passes values to a child through props, and the child can pass them on to its own children. A component cannot reach up and read a value from an ancestor unless that ancestor handed it down.
Prop drilling happens when a value is needed by a component deep in the tree, and the only way to deliver it is to pass it through every component in between. The in-between components are called intermediaries. They accept the prop only to forward it.
A worked example
Here is a small app. App owns the current user. Avatar, four levels down, needs the user to draw a picture.
import { useState } from 'react';
function App() {
const [user] = useState({ name: 'Ada', avatarUrl: '/ada.png' });
return <Layout user={user} />;
}
function Layout({ user }) {
return (
<div className="layout">
<Sidebar user={user} />
<main>Main content</main>
</div>
);
}
function Sidebar({ user }) {
return (
<aside>
<nav>Links</nav>
<UserMenu user={user} />
</aside>
);
}
function UserMenu({ user }) {
return (
<div className="user-menu">
<Avatar user={user} />
</div>
);
}
function Avatar({ user }) {
return <img src={user.avatarUrl} alt={user.name} width="32" height="32" />;
}
export default App;Only App (the owner) and Avatar (the consumer) care about user. Layout, Sidebar and UserMenu each declare a user parameter and pass it along unchanged. The data takes the path shown below.
With four levels and one prop, this is tolerable. Real applications have more levels, more values and more components that need them.
Why it becomes a problem
The cost of drilling grows with the depth of the tree and the number of values you pass. It shows up in several ways.
- Changes ripple through unrelated files. Suppose
Avataralso needs atheme. You must editApp,Layout,Sidebar,UserMenuandAvatar. Three of those edits have nothing to do with theming. - Intermediaries become coupled to data they do not use.
Sidebarnow "knows" aboutuser. If you reuseSidebarelsewhere, you must supply auserit does not need. - Refactors are risky. Moving
Avatarto a different part of the tree means rebuilding the chain of props along its new path. Forgetting one link producesundefinedat runtime. - Components are harder to read and test. A component with eight props, six of them forwarded, hides which ones it actually depends on. Tests must supply values for all of them.
- Names drift. One level calls the prop
user, the nextcurrentUser, the nextprofile. Searching for where a value comes from gets harder.
A table of the earlier example after adding theme makes the effect concrete.
| Component | Uses `user` | Uses `theme` | Must change to add `theme` |
|---|---|---|---|
| `App` | Owns it | Owns it | Yes |
| `Layout` | No | No | Yes |
| `Sidebar` | No | No | Yes |
| `UserMenu` | No | No | Yes |
| `Avatar` | Yes | Yes | Yes |
Five edits are needed to deliver one value to one component.
Drilling is not always wrong
Passing props down is how React is meant to work. It is explicit: you can follow a value by reading the code. Do not treat every forwarded prop as a defect.
Drilling is usually fine when:
- the chain is two or three levels deep;
- the intermediaries use or relate to the value in some way;
- the value is specific to one part of the tree and unlikely to be needed elsewhere.
It starts to hurt when:
- the same value is forwarded through components that never use it;
- many distant components need the same value, such as the current user, the theme or the locale;
- adding a new value requires edits across many files.
A rough test is to look at a component's parameter list. If it destructures a prop only to hand it to a child, ask whether it should know about that value at all.
Option 1: restructure with composition
Before using context, check whether the tree can be rearranged. Often the intermediaries pass data only because they build the child components themselves. If a parent receives children as props, it can render whatever it is given without knowing what that content needs.
This version builds Avatar in App, where user already lives. The layout components receive ready-made elements.
import { useState } from 'react';
function App() {
const [user] = useState({ name: 'Ada', avatarUrl: '/ada.png' });
return (
<Layout
sidebar={
<Sidebar>
<UserMenu>
<Avatar user={user} />
</UserMenu>
</Sidebar>
}
/>
);
}
function Layout({ sidebar }) {
return (
<div className="layout">
{sidebar}
<main>Main content</main>
</div>
);
}
function Sidebar({ children }) {
return (
<aside>
<nav>Links</nav>
{children}
</aside>
);
}
function UserMenu({ children }) {
return <div className="user-menu">{children}</div>;
}
function Avatar({ user }) {
return <img src={user.avatarUrl} alt={user.name} width="32" height="32" />;
}
export default App;Now user is passed exactly once, from App to Avatar. Layout, Sidebar and UserMenu no longer mention it. Adding theme means editing only App and Avatar.
Composition has limits. It moves complexity upward: App now assembles a large part of the page, and it may become crowded if many pieces need wiring. It also works best when the consumer can be created at the top. It fits poorly when the same value is needed in many unrelated places, or when a component deep in the tree must read a value that changes by region.
Option 2: keep drilling, but make it cheap
For short chains, plain props remain the clearest choice. You can reduce the pain without changing the design:
- pass one well-named object, such as
user, rather than five separate fields that all travel together; - keep intermediaries small, so the forwarded props are easy to see;
- use TypeScript or PropTypes so that a broken link fails early.
Option 3: context
Some data is needed by many components at different depths, and composition does not fit it. Common examples are the current user, the color theme, the interface language and the router location. For these, React provides context. A component high in the tree supplies a value, and any component below it can read that value directly. The intermediaries do not take part.
The next chapters build this up step by step: creating a context, providing a value, reading it and managing the re-render behavior it brings. Context is not free. It has its own trade-offs, and a later chapter returns to the question of when it is the wrong tool.
Common mistakes
- Reaching for context at the first forwarded prop. Two or three levels of explicit props are easier to follow than a hidden dependency.
- Using a spread to hide drilling.
{...props}keeps the coupling and removes the readability. - Lifting state higher than needed. Putting state in
Appbecause a distant component needs it forces drilling. Often the state can live closer to where it is used. - Not considering composition. Many drilling problems disappear when a parent accepts
childrenor named slot props. - Copying the value into each level's state. Duplicating a prop into local state at every layer causes values to get out of sync.
Exercise
In the first example, Sidebar receives a user prop and passes it to UserMenu, but never reads it. A new requirement says Avatar must also receive a onLogout callback defined in App. Which components must change if you keep using props, and how would the composition approach from this chapter change that?
Show answer
With plain props, all five components must change: App defines onLogout and passes it to Layout, then Layout, Sidebar and UserMenu each add the parameter and forward it, and Avatar finally uses it. With composition, only App and Avatar change. App already creates <Avatar user={user} />, so it adds onLogout={handleLogout} there, and Avatar accepts the new prop. Layout, Sidebar and UserMenu only render children or a slot, so they stay untouched.
Exercise
A teammate has a component that forwards six props to a child and uses none of them. Name two ways to remove the forwarding, and name one situation where leaving the props alone is the better choice.
Show answer
Two ways are to restructure with composition, so the parent receives children or slot props and the owner creates the consumer directly, and to use context for values needed by many distant components. Leaving the props alone is better when the chain is short, perhaps two or three levels, because explicit props are easy to trace and no hidden dependency is added.