Alex Sidorenko

Prop drilling and component composition in React

March 02, 2023

Sometimes all we need to avoid prop drilling is a little restructuring:

Real-world example

Let’s 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 exactly do 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 a child component.

Now let’s 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’t 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.

Do you have any questions? Send them as a reply to my last email. Not a subscriber yet? 👇