Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 23, 2021 04:58 pm GMT

What is Prop Drilling in React? Understanding Context API - Part 1

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.

prop drilling in react

Prop Drilling by Example

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:

  1. Context.Provider
  2. 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


Original Link: https://dev.to/varunprashar5/what-is-prop-drilling-in-react-understanding-context-api-part-1-381l

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To