React / 61
Prop drilling, and two ways out
Passing a prop through components that don't use it, just to reach one deep down. Fix it with composition (children) first, and Context when that's not enough.
What it looks like
The logged-in user lives in App, but only UserMenu, three levels down, uses it:
export default function App() {
const user = { name: "Asha" };
return <Layout user={user} />;
}
function Layout({ user }) {
return (
<div className="page">
<Header user={user} /> {/* doesn't use user, just forwards it */}
</div>
);
}
function Header({ user }) {
return (
<header>
<UserMenu user={user} /> {/* same here */}
</header>
);
}
function UserMenu({ user }) {
return <p>Hi, {user.name}</p>;
}Layout and Header are just couriers. Add a cartCount that UserMenu also needs, and you edit all four components.
Prop drilling
pass it hand to hand
owns the data
doesn't use it, passes it on
doesn't use it, passes it on
finally uses it
Context
put it in the tree, read it where needed
owns the data, wraps its children in a provider
<UserContext value={user}>
no user prop
no user prop
reads the nearest provider
Way out 1: composition (try this first)
Often the middle components don't need to render the deep one themselves. Let them accept children instead, and the top component can place UserMenu directly, with its props:
export default function App() {
const user = { name: "Asha" };
return (
<Layout>
<Header>
<UserMenu user={user} />
</Header>
</Layout>
);
}
function Layout({ children }) {
return <div className="page">{children}</div>;
}
function Header({ children }) {
return <header>{children}</header>;
}user now goes straight from App to UserMenu. Layout and Header know nothing about it, so they're simpler and more reusable. No new API needed.
Way out 2: Context
When many components at different depths need the same data (the current user, the theme, the language), composition gets awkward. Context lets a parent put a value into the tree, and any component below can read it directly, no matter how deep. That's the next topic.
Further still, apps with lots of shared, frequently changing state often use a state library like Redux Toolkit, which gets its own chapter.
Gotchas
Recall
Can you answer these?
0/4
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
