Props Drilling In React.Js

Hadeel Salah
Frontend Weekly
Published in
3 min readSep 14, 2020

--

Profile-Image

First of all, let us just be thankful for Leonardo DiCaprio. Are you curious why? Let us know why ;)

This article will cover two topics:

  • What props drilling is
  • How to sidestep props drilling

Let’s start the party!

What is Props Drilling?

Let’s recap what we know first about the Props concept. Props are the data we pass -or can access- from the top-level components to any number of child components on our website. Look at Diagram -1-

Diagram-1-

Props Drilling(also know as threading ) is when diagram -1- transform to be like this.

Diagram-2-

From diagram 2, the Props Drilling (Threading) is a concept that refers to the process you pass the data from the parent component to the exact child Component BUT in between, other components owning the props just to pass it down the chain.

So, what is the link between Props Drilling and Leo?

Well, Leo has been nominated 7 times for the Oscars, and once he won one time in his movie “Revenant”.However, in the React.js world, his name is the props you passed to more than one level even they don’t need it until it reaches the one that you use props in.

You can see the code by this link.

2. How To Sidestep Props Drilling.

There are several solutions to avoid props drilling :

1. React Context API.

2. Composition

3. Render props

4. HOC

5. Redux or MobX

Avoid Props By Drilling Using React Context API

First, you need to initialize the context. You can do that in the js file or in the top of the parent component.
const MyContext = React.createContext() ;

After that, move on to create your provider and use the context in it. Then, we need to use the context and warp the component with it which injects the context argument in it.

Afterward, it is pretty straight forward. You can use the context in the same way you used props.

Note: You can see the code here

Congrats, you did it.

2. Avoid Props Drilling By Composition

Simply, to compose the react component, you have to divide the component to containers and presenters -stateful and stateless-. Then pass the data as props to children.

So, the main component will be like this:

and list movies component will contain all the components like this:

Here, pass the props to the Revenant component.

You can see the full code here

Bravo, You finished successfully

See you in the next couple of articles which I will explain the other solutions ;)

--

--

Hadeel Salah
Frontend Weekly

Hunger for Knowledge, adventure, and risk enthusiastic. Software engineering student