Prop Drilling
๐น What is Prop Drilling?
Prop drilling is the process of passing data (props) from a parent component down to deeply nested child components through intermediate components.
Even if some middle components donโt need the data, they still have to pass it along.
๐น Basic Flow
Parent โ Child โ Grandchild โ GreatGrandchild
Data travels step-by-step through each level.
๐น Simple Example (Passing Data)
โ Parent Component
function Parent() {
const message = "Hello from Parent!";
return <Child message={message} />;
}
โ Child Component
function Child(props) {
return <GrandChild message={props.message} />;
}
โ GrandChild Component
function GrandChild(props) {
return <h1>{props.message}</h1>;
}
โ
Result:
The message flows like this:
Parent โ Child โ GrandChild
Even though Child doesnโt use message, it must forward it.
๐น Passing Functions as Props
You can also pass functions down the same way.
โ Parent Component
function Parent() {
const showAlert = () => {
alert("Button clicked!");
};
return <Child onClick={showAlert} />;
}
โ Child Component
function Child(props) {
return <GrandChild onClick={props.onClick} />;
}
โ GrandChild Component
function GrandChild(props) {
return <button onClick={props.onClick}>Click Me</button>;
}
โ What happens:
GrandChildbutton click โ calls function from ParentData flow is still top โ down, but events can bubble back via functions
๐น Why is it called "Drilling"?
Because you're โdrillingโ props through layers of components:
Parent
โ
Child (doesn't need data)
โ
GrandChild (actually uses data)
๐น Problem with Prop Drilling
It becomes messy when:
Many nested components
Too many props being passed
Intermediate components donโt need the data
โ Example Issue
<Level1 data={data}>
<Level2 data={data}>
<Level3 data={data}>
<Level4 data={data}>
Hard to maintain and debug ๐ต
๐น Solutions to Avoid Prop Drilling
When prop drilling becomes too much, use:
โ 1. Context API
Lets you share data globally
const MyContext = createContext();
โ 2. State Management Libraries
Redux
Zustand
Recoil
โ 3. Component Composition
Sometimes restructure components instead
๐น Quick Visual Summary
โ Data flow:
Parent โ Child โ GrandChild
โ You can pass:
variables โ
functions โ
objects โ
โ Issue:
- unnecessary passing through components
๐น Interview Tip
โ Define it simply:
Prop drilling is the process of passing props from a parent component to deeply nested child components through intermediate components, even if those components do not use those props.
โ Final Takeaway
Prop drilling = passing props down multiple levels
Works fine for small apps โ
Becomes messy in large apps โ
Use Context or state libraries when needed โ