Alex Sidorenko AvatarAlex Sidorenko

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.

App layout with navigation and sub navigation

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:

[
{ "label": "Home", "href": ... },
{ "label": "About", "href": ... }
{
"label": "Account",
"sub": [
{"label": "Profile", "href": ...},
{"label": "Subscriptions", "href": ...}
]
}
];

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.


Follow me on 饾晱 for short videos about Next.js

饾晱 Follow for more