React
/Intermediate
Prop Drilling
Definition
Prop drilling is the process of passing data from a high-level parent component down to a deeply nested child component through multiple layers of intermediate components that do not actually need the data.
Explain Like I'm New
Imagine the CEO on floor 5 wants to give a package to a worker on floor 1. The CEO hands it to the VP on floor 4, who hands it to a Manager on floor 3, who hands it to a Supervisor on floor 2, who finally gives it to the worker. The people on floors 2, 3, and 4 don't care about the package; they are just acting as delivery drivers. This is Prop Drilling, and it makes code messy.
Real World Example
Passing a `theme` prop (`dark` or `light`) from `<App>` through `<MainLayout>`, `<Dashboard>`, and `<Sidebar>` just so a single `<ThemeToggleButton>` can use it.
Common Use Cases
- •Prop drilling is actually perfectly fine for 1-3 levels deep. It keeps data flow explicit and easy to trace.
- •It becomes an anti-pattern when it passes through 5+ layers or through components that should be completely ignorant of the data.
Interactive Example
import React, { useState } from "react"; export default function TopLevelApp() { const [user, setUser] = useState({ name: "Alice", role: "Admin" }); return ( <div className="p-4 border border-blue-500"> <h2>Level 1: Top App</h2> <MiddleLayout user={user} /> </div> ); } // This component doesn't care about "user", it just drills it down function MiddleLayout({ user }) { return ( <div className="p-4 border border-green-500 ml-4"> <h3>Level 2: Middle Layout</h3> <DeepDashboard user={user} /> </div> ); } // This component doesn't care about "user" either function DeepDashboard({ user }) { return ( <div className="p-4 border border-yellow-500 ml-4"> <h4>Level 3: Dashboard</h4> <DeepestUserAvatar user={user} /> </div> ); } // Finally, the component that actually uses the data! function DeepestUserAvatar({ user }) { return ( <div className="p-4 border border-red-500 ml-4"> <h5>Level 4: Avatar (Destination)</h5> <p>Name: {user.name} | Role: {user.role}</p> </div> ); }
Interview Questions
basic
- What is Prop Drilling?
- Is Prop Drilling always a bad thing?
intermediate
- What are the main drawbacks of excessive Prop Drilling?
- How does the Context API solve Prop Drilling?
advanced
- How can Component Composition (passing children) be used to avoid Prop Drilling without using Context?
- If an intermediate component re-renders during Prop Drilling, what happens to the nested child?
trick
- Does Prop Drilling inherently cause performance issues?