How to Eliminate Prop Drilling in React with Component Composition
This article explains how to avoid prop drilling in React by refactoring components to use composition and children props, providing a clear example with a navigation sidebar and discussing alternatives like Context and Redux.
This article, translated from the original “Prop drilling and component composition in React”, explains how to solve the prop drilling problem in React by using component composition.
Prop drilling occurs when a state held in a top‑level component must be passed through intermediate components that do not need it, using props layer by layer.
Example
Consider a dynamic navigation sidebar that receives data from a server and renders the navigation based on that data.
The JSON data used for rendering is simplified as follows:
<code>[
{ "label": "Home", "href": "..." },
{ "label": "About", "href": "..." },
{
"label": "Account",
"sub": [
{ "label": "Profile", "href": "..." },
{ "label": "Subscriptions", "href": "..." }
]
}
];</code>These data need to be supplied to components such as NavList, NavItem, SubNavList, and SubNavItem. One naïve implementation passes the data through each component via props, which leads to extensive prop drilling.
To avoid this, we refactor the components to use
childrenso that each component becomes more independent:
After refactoring, a set of simple, independent components can be rendered directly inside the Sidebar, eliminating the need to pass props through unrelated layers.
This approach prevents prop drilling, makes components adaptable to different data structures, and allows reuse in various locations.
If we prefer not to handle data processing inside the Sidebar, we can move that logic to a separate component.
Summary
The article demonstrates that using composition (the
childrenprop) resolves prop drilling in React. While React Context or Redux can also avoid prop drilling, they introduce tighter coupling between parent and child components, reducing independence and reusability.
KooFE Frontend Team
Follow the latest frontend updates
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.