DEV Community

Hihi
Hihi

Posted on • Edited 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:

    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/

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay