If you have started learning or exploring react then you must have come to a situation where you are passing your props down to 3rd - 4th or Nth level in your components hierarchy.
The intermediary components need not do anything with those props but are acting as a pathway to pass those props to the child which actually needs them.
This particular problem is called "Prop Drilling".
In the cover image, you can see that I am actually passing "Complete Todo" and "Delete Todo" from my TodoApp component down to the "Todo" Component.
TodoList component needs nothing to do with these props and is acting as an intermediary here.
Few problems with Prop Drilling:
- Useless re-renders will be there in case that prop is changed from the parent via an event
- Easy to maintain the code in case there is a change request and is prone to errors
- Becomes very difficult when we have a deeper level of nesting and we are passing the props
How can we prevent this Prop Drilling?
We can prevent it by using "Context API" in React. It has two components named:
- Context.Provider
- Context.Consumer
Apart from that, we can even use the "useContext" hook instead of Context. Consumer and is a preferred way.
If we can combine Context API with useReducer Hook, It can be a powerful tool for having our own central state management.
But it is suggested by React team that we should only use "Context API" in case we have less frequent updates in these props.
Do follow me on:
Linkedin: https://www.linkedin.com/in/varunprashar5/
Twitter: https://twitter.com/Varunprashar
Top comments (1)
why not redux, react-query?