Prop Drilling in React.js
Prop drilling aka threading in React.js refers to the process when we have to pass some data through one component to another in the React component tree. The data sharing process between the components is unidirectional.
Let’s see the below diagram:
Suppose I want to pass the data from Component A to Component C, it will pass down as a prop (prop B in the image) and then passed to Component C using prop C. So, this is what prop drilling is.
Now, let’s see a code example below:
In this example, I have created a function called isAvailable to check if Jack is available or not (let’s say for a ride).
I have drilled the props through Status component even if it’s of no use but its children are in need of those check state and avail handler. This is prop drilling.
The upside of prop drilling
Prop drilling makes it really easy and fast to pass data between components when you are building small applications and it’s an easy method as compared to other methods available for data transfer.
Another advantage of using prop drilling is that the data passed as props can easily be updated on state change to reflect the changes in the output.
The downside of prop drilling
When it comes to big-scale applications, prop drilling can make the code complicated. Sometimes props can be passed to the component tree just to get the data to the child component which leads to an unnecessary increase in the codebase. One more problem is that it’s really difficult to keep track of the props after renaming them at some point since the codebase will be large and eventually it will not be easy to remember these little things.
Conclusion
Prop drilling should only be used in small scale applications for transferring data from one component to another and it can mess up with a large codebase. So, it’s not a good choice if you are using it in large scale applications.