Skip to content
ClapelloNotes by Barath
ReactCh 11 · 4/6
Beginner3 min readUpdated

React / 61

Prop drilling, and two ways out

TL;DR

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:

App.jsx
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

<App>const user

owns the data

user={user}
<Layout>user

doesn't use it, passes it on

user={user}
<Header>user

doesn't use it, passes it on

user={user}
<UserMenu>user

finally uses it

Context

put it in the tree, read it where needed

<App>const user

owns the data, wraps its children in a provider

<UserContext value={user}>

<Layout>

no user prop

<Header>

no user prop

<UserMenu>useContext

reads the nearest provider

Prop drilling: every level carries user, even the ones that never look at it. Context: the provider puts user in the tree, and only the component that needs it reads it.

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:

App.jsx
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.