What is prop drilling and how do you avoid it?
Prop drilling is the pattern of passing data through many layers of components just so a deeply nested child can use it — even though intermediate components don't need it. Tedious, noisy, and brittle to refactor.
Context API — React's built-in solution;
createContext+useContextshare data across the tree without manual passing.State libraries — Redux, Zustand, Jotai, Recoil for app-wide state with finer control over re-renders than Context.
Server state libraries — React Query, SWR hold remote data; any component that needs it just calls the hook.
Composition — passing children as props or using compound components often eliminates the need to drill at all.
Use Context sparingly — every consumer re-renders on context change; split contexts by concern (theme, auth, locale).
// PROBLEM: Prop drilling
function App() {
const [user, setUser] = useState({ name: 'John' });
return <Layout user={user} />; // Layout doesn't need user
}
function Layout({ user }) {
return <Sidebar user={user} />; // Sidebar doesn't need user
}
function Sidebar({ user }) {
return <UserMenu user={user} />; // Only UserMenu needs user
}
// SOLUTION: Context API
const UserContext = createContext();
function App() {
const [user, setUser] = useState({ name: 'John' });
return (
<UserContext.Provider value={user}>
<Layout /> {/* No user prop needed */}
</UserContext.Provider>
);
}
function Layout() { return <Sidebar />; } // Clean!
function Sidebar() { return <UserMenu />; } // Clean!
function UserMenu() {
const user = useContext(UserContext); // Direct access
return <span>{user.name}</span>;
}In the prop drilling version, user passes through Layout and Sidebar unnecessarily. In the Context version, UserContext.Provider wraps the tree, and only UserMenu calls useContext to access the data.
Layout and Sidebar are unaware of user data, making them simpler and more reusable.
Show the problem (verbose intermediate components) and multiple solutions (Context, composition, state libraries). Mention that Context is not always the answer — it causes re-renders for all consumers when the value changes.