There are 2 common ways to solve Props drilling in React: use ContextAPI/Redux
and use React Composition. In this article i will go through the ContextAPI usage and React composition.
Drawback of Context
in solving Prop drilling in React: reusability.
For example, you have the ProfileComponent
deep nested, and you want to use the userData
defined in the container with User.Provider
and other Context
things:
What if we want to use userData
in other container? The userData in Checkout
component would be undefined
.
Context is suitable for passing props to many different component under 1 nested Provider:
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>
)
}
The userData
is passed right away from the container, not having to go through parent components.
Cons of React Composition in this context:
- 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.
- Upper-parent components still rerender when the states change although they don't consume the state => to solve this use API Context or Redux store.
References:
felixgerschau.com/react-component-composition reactjs.org/docs/context.html#when-to-use-c.. kentcdodds.com/blog/prop-drilling frontendmastery.com/posts/advanced-react-co..