DEV Community

Cover image for Drilling in React
ckorley4
ckorley4

Posted on

Drilling in React

Props are used by react to pass information from one component to another

There are situations that require information to go from Parent component to child component and to Grandchildren

How to avoid prop drilling
In case, when you project become larger and more complex, prop drilling can become a problem. To avoid this problem in React-based projects, there are several patterns and techniques that can be used:

React Context
React Context is a way to share data across the component hierarchy without passing it down explicitly as props. Context can be a good alternative to prop drilling when you need to share data across multiple components.
The problem with Prop Drilling is that whenever data from the Parent component will be needed, it would have to come from each level, Regardless of the fact that it is not needed there and simply needed in last.

With Context, you can define data at the top level of the component tree and then access it anywhere in the tree. This can help reduce the amount of code you need to write, and make it easier to manage and share data across the component hierarchy.

Drawbacks of Drilling
Code Complexity
As components grow, prop drilling increases code complexity as it is difficult to track the flow of data through various components.
Reduced Maintainability
It will become very challenging to maintain the code with prop drilling. When changes are required in the data flow, you need to make changes in many components.

Performance Overhead We have to pass props through unnecessary intermediary components which can impact performance.

Decreased Component Reusability
Components used in prop drilling become tightly coupled to the structure of the parent components, so it very difficult to use it on other parts of the application.
Increased Development Time: Prop drilling often requires additional planning to implement. This can slow down the development process, especially when the component hierarchies is complex.

A better alternative to this is 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.

Resources
https://www.geeksforgeeks.org/what-is-prop-drilling-and-how-to-avoid-it/
https://javascript.plainenglish.io/prop-drilling-in-react-understanding-the-benefits-and-pitfalls-of-passing-props-down-the-component-fcf9887f8b73

Top comments (0)