2 Mar 2023
Prop drilling and component composition in React
Sometimes all we need to avoid prop drilling is a little restructuring:
Real-world example
Let鈥檚 say we have this UI structure.
The navigation is dynamic. The Sidebar receives the data from the server and renders navigation based on this data.
How we get this data is not that important for our example.
The simplified version of the JSON for our navigation could look like this:
We need to map this data to our components (NavList
, NavItem
, SubNavList
, SubNavItem
). One way of doing this is to let the components render each other and pass the data along the way.
This will do the job. However, this structure involves a lot of prop drilling. Every intermediate component should be aware of the props it receives and understand how to pass those props down and render child components.
Now let鈥檚 restructure our components to make them independent from their surroundings using the children
prop.
And now that we have a set of simple independent components, we can render them directly in the Sidebar
.
This avoids prop drilling and creates a set of independent components that can be reused in different places with different data structures.
And if we don鈥檛 want to do the data mapping directly in the Sidebar
, we can move it into a separate component.
Coding challenge
Can you refactor the Dialog
and DialogFooter
components using the children
prop and restructure them in HelloWorldDialog
to avoid prop drilling? CodeSandbox.