Props drilling in React

ngquan

Hihi

Posted on September 19, 2022

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:

    App
     |-- 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?

App
  |-- 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 (
        <Homepage>
            <Component1>
                <Component3 data={userData} />
            </Component1>

            <Component2>
                <Component4 />
                <Component5>
                    <Component6 data={userData} />
                </Component5>
            </Component2>
        </Homepage>
    )
}

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.

References:
https://felixgerschau.com/react-component-composition/
https://reactjs.org/docs/context.html#when-to-use-context
https://kentcdodds.com/blog/prop-drilling
https://frontendmastery.com/posts/advanced-react-component-composition-guide/

💖 💪 🙅 🚩
ngquan
Hihi

Posted on September 19, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related