DEV Community

Cover image for Prop Drilling
ayush65
ayush65

Posted on • Updated on

Prop Drilling

Components in React can be passed some parameters. These parameters are generally named props.

When i started learning in React . I came across Prop drilling it . Prop drilling is basically a situation when the same data is being sent at almost every level due to requirements in the final level. Data needed to be sent from Parent to Child.

The diagram can be given as :-

output

React has a component based design like:-

  • App.js
  • Post.js
  • login.js
  • Feed.js
  • Header.js
  • Sidebar.js

output

The App.js is the main parent here it first checks with the Login.js for the authentication of the user then the details is been send to the feed section for further details .

assume when we login we get the user for the user object . then if we have to pass the user through the tree it will be messy and hard to understand .

The Prop Drilling helps to traverse the data requied in this case we have the user details after login in then the data is been send to the feed as per the user then we can fetch the data of the user as in the form of posts.

-> Why is Prop Drilling a Problem?

Prop drilling doesn’t have to be a problem. If we are passing data only between 2 or 3 levels, we are fine. It will be easy to trace the flow of data but if we are drilling 5 levels, or 10 levels, or 15 it will be a problem because the data will have to traverse all through the levels .

-> So how can we prevent this from happening ?

We can actually use react context .

React context can help us to pass the data through to all the components in the tree , without taking too much time to pass it down every level .

output

In our case we want the user details to be given to the required place . Assume we want the user details in the post part to know that what posts the user has made as per the user id or personal details . After getting the details the post part will only show the posts and we do not have to pass the user details throughout the tree.

-> Without using Prop Drilling

                     useContext hook
Enter fullscreen mode Exit fullscreen mode

We can use alternative by using useContext hook. The useContext hook is based on Context API and works on the mechanism of Provider and Consumer. Provider needs to wrap components inside Provider Components in which data have to be consumed. Then in those components, using the useContext hook that data needs to be consumed.

Thanks for your time , Have a nice day πŸ˜„

Top comments (0)