React Interview Question: How Do You Avoid Prop Drilling?
Short answer: prop drilling is passing props through several intermediate components that don't use them, just to reach a deeply nested child. Fix it with composition first, then Context, then a state library for complex shared state.
The problem
<App user={user}>
<Layout user={user}> {/* doesn't use user */}
<Header user={user}> {/* doesn't use user */}
<Avatar user={user} /> {/* finally uses it */}
Every layer must know about user, and refactoring touches all of them.
Solution 1: composition
Pass the finished element down instead of the data:
function App() {
const user = useCurrentUser();
return (
<Layout header={<Header avatar={<Avatar user={user} />} />}>
<Dashboard />
</Layout>
);
}
Layout and Header just place what they're given. Often overlooked, and it needs no extra API.
Solution 2: Context
const UserContext = createContext(null);
function App() {
const user = useCurrentUser();
return (
<UserContext value={user}>
<Layout />
</UserContext>
);
}
function Avatar() {
const user = use(UserContext); // or useContext(UserContext)
return <img src={user.avatarUrl} alt={user.name} />;
}
Great for app-wide values that change rarely: current user, theme, locale.
Solution 3: a state library
For frequently updated state shared across many parts of the app, a store like Zustand or Redux Toolkit lets components subscribe to exactly the slice they need without re-rendering everything.
Bonus
Mention that passing props two or three levels is perfectly fine and explicit. Reach for these solutions when drilling becomes painful, not by default.
Comments
No comments yet. Have a question or a tip? Be the first to share it.