DEV Community

Cover image for React Component Composition - Why does it matter?
Brenden Olding
Brenden Olding

Posted on

React Component Composition - Why does it matter?

In React there are a lot of flashy tools (hooks) that can do a lot of things for you. useContext() has seen a lot of love as a way to avoid 'prop drilling', but what if I told you there was another way?

If you are simply trying to avoid 'prop drilling' in React there is an incredible prop you can use to avoid that. The children prop is under used, but incredibly powerful.

Children Prop - What is it?

The children prop is almost self-explanatory. You use the prop in your component as such:

const Home = ({children}) => {
    return (
    <div>
        <h1>Welcome to My Blog</h1>
        {children}
    </div>
    )
}
Enter fullscreen mode Exit fullscreen mode

It may not seem like it is doing much in this instance, but it can open up a world of opportunities to avoid that pesky 'prop drilling'. In this example Home component, you can display nested components inside the Home component and go multiple layers deep without passing props through each layer. Say you have a component 3 nested components deep; you can pass the children component to each of the 'parent' components and render each nested component as a child of the 'parent'. Here is what your App component could look like that in this instance:

const App = () = {
return (
  <div>
   <Home>
    <Component1>
     <Component2>                                                
      <DeepestComponent neededProps={/*whatever                      
      variables, functions, or state you need*/} />
     </Component2>
    </Component1>
   </Home>
  </div>
)
}
Enter fullscreen mode Exit fullscreen mode

In this example instead of rendering Component1 inside the Home component, and Component 2 inside Component1, and the DeepestComponent inside of Component2, you render the children prop inside each parent and use composition to your advantage. So, in this example you can avoid props drilling from App all the way down through Home, Component1, Component2, and finally the component that needs it, DeepestComponent. Instead, you just pass the props straight to the DeepestComponent from the App Component.

There are of course drawbacks to this method, like "What if I need to pass props from Component1 to DeepestComponent?" or any other issues where state is necessary at multiple levels. In these cases, use useContext(), but if you aren't encountering an issue like that, you can use Component composition to your advantage.

Sources Referenced:

Using Composition in React to Avoid "Prop Drilling"
Flatiron School Curriculum on React Context and Children Props

Top comments (0)