DEV Community

Cover image for Prop Drilling in React
ABISHEK M
ABISHEK M

Posted on

Prop Drilling in React

In React, props are used to pass data from a parent component to a child component. Props are an important part of React because they allow components to share information. However, when data needs to travel through many levels of components, it can lead to a situation called Prop Drilling.

Prop drilling means passing data from a parent component to a deeply nested child component through intermediate components, even when those intermediate components do not need the data.

For example, imagine the component structure:

App
 ↓
Parent
 ↓
Child
 ↓
GrandChild
Enter fullscreen mode Exit fullscreen mode

Suppose the App component has a username that is required by GrandChild.

function App() {
  const username = "Abishek";

  return <Parent username={username} />;
}
Enter fullscreen mode Exit fullscreen mode

The Parent component receives the username and passes it to Child:

function Parent({ username }) {
  return <Child username={username} />;
}
Enter fullscreen mode Exit fullscreen mode

Then Child passes it to GrandChild:

function Child({ username }) {
  return <GrandChild username={username} />;
}
Enter fullscreen mode Exit fullscreen mode

Finally, GrandChild uses the username:

function GrandChild({ username }) {
  return <h1>Hello {username}</h1>;
}
Enter fullscreen mode Exit fullscreen mode

Here, Parent and Child don't actually use the username. They only pass it to the next component. This is called prop drilling.

Prop drilling is not always a problem. If data only passes through one or two components, normal props are simple and useful. However, when data needs to pass through many levels, the code can become difficult to read, maintain, and modify.

React provides solutions such as the Context API to avoid unnecessary prop drilling. Context allows deeply nested components to access shared data without manually passing props through every intermediate component.

In simple terms:

Props: Parent → Child
Prop Drilling: Parent → Child → Grandchild → Deep Child

Understanding prop drilling helps developers decide when normal props are sufficient and when a different approach to sharing data would make the application easier to manage.

Top comments (0)