Lesson 14 of 80
Passing a component as a child instead of configuring it with props — a second, often simpler answer to the same prop-drilling problem Context solves.
12 min read
Every option explains itself — why the right one is right, and why each wrong one is wrong. Miss one and it comes back later on a spaced-repetition schedule.
Question 1 of 2
In `<Panel><UserProfile user={currentUser} /></Panel>`, does Panel need to know that currentUser exists?
Hints without spoilers, and a plain explanation of why a wrong answer was wrong — answered only from this lesson. Free account, no card.
Sign up freeWhat interviewers actually ask about this, and what a strong answer has to cover.
A strong answer covers
Likely follow-ups
Instead of a component reaching deep into its children's configuration via a long list of props, you can hand it already-built React elements through children (or a named prop) and let it just render them wherever it wants:
function Panel({ children }) {
return <div className="panel">{children}</div>;
}
function App() {
return (
<Panel>
<UserProfile user={currentUser} /> {/* Panel never sees currentUser */}
</Panel>
);
}
Panel has no idea UserProfile or currentUser exist — App, which already has currentUser in scope, builds <UserProfile> directly and hands the finished element to Panel to place. Nothing had to be threaded through Panel's own props.
<Panel><UserProfile user={currentUser} /></Panel> — App builds UserProfile directly, with the data already in scope.
Both composition and Context solve "a deeply nested descendant needs something an ancestor has, without every component in between caring about it" — but differently:
Layout).children isn't limited to one slot. You can accept multiple named "slot" props (<Layout header={...} sidebar={...} main={...} />) for components that need several independent regions.Panel re-rendering (say, from its own internal state) doesn't have to re-render UserProfile if UserProfile was passed in as children from App — the element reference passed down didn't change.<Outlet> and layout components work — a component in the middle of the tree that has no idea what's actually being rendered inside it."How would you avoid prop drilling without reaching for Context?" checks whether composition is actually in your toolkit — many candidates only know Context as the fix, when composition is often the simpler, more idiomatic one.