DEV Community


Posted on • Updated on

Props drilling in React

There are 2 common ways to solve Props drilling in React: use ContextAPI/Redux and use React Composition.

Drawback of Context in solving Prop drilling in React: reusability
For example, you have the User component deep nested, and you want to use it in other Provider:

     |-- Homepage
           |-- User.Provider
                   |-- ... WhateverComponents
                         |---- ProfileComponent => use userData from provider here

Enter fullscreen mode Exit fullscreen mode

What if we want to use userData in other container?

  |-- Homepage
  |        |-- User.Provider
  |            |-- ... WhateverComponents
  |                  | ...
  |-- Cart (what if we want to use userData in here?) userData will be empty here!

Enter fullscreen mode Exit fullscreen mode

Context is suitable for passing props to many different component under 1 nested Provider:

Image description

There's a way to solve Props Drilling, that is Component compose
We can re-write the above structure in code like this:

// app.tsx
const App = () => {
    const userData = {...}
    return (
                <Component3 data={userData} />

                <Component4 />
                    <Component6 data={userData} />

Enter fullscreen mode Exit fullscreen mode

the userData is pass right away from the container, not having to go thru parent components. This can also improve performance thus when the userData changes, only the components use it will re-render.

Cons of React Composition: when your container grows larger and larger it may cause so much deep nested components layer. To this problem, we should consider split them into smaller components and decide wisely which props should each container need and hold.


Top comments (0)