In react Prop Drilling
is a common situation that a developer will encounter, before knowing ways to avoid it, let's first understand what's prop drilling and why one should avoid it.
Prop Drilling
Prop drilling is nothing but the passing of prop from parent to child components which is many levels deep in the component tree, and between this parent and child component there are other child components that don't need this prop, but still, we have to pass the prop through this components to reach the child component where we need this prop, this is called as prop drilling.
Let's see this with an example, you can try it as well in any code editor.
As you can see above, in the component App
there is a count state, which we have to pass through components A and B, in order to use that state in component C, even though components A and B are not using that state, this is the issue with prop drilling.
Ways to Resolve Prop Drilling
This problem we can solve if we create some kind of a global state or data, which we can access from any component, then we will not have to pass the prop through components to access the state and this can be achieved by useContext hook
.
useContext Hook
As you can see in the above implementation using useContext hook, we were able to avoid prop drilling.
I hope this was helpful in clearing your doubts regarding the prop drilling and do let me know what you think about this article, you can connect with me on Linkedin