Avoid Prop Drilling using Composition

In react when we pass a props down to its children, we like to use Context/Redux, this is not wrong but we don’t need to use this every time if parent has a small amount of children or child components don’t have any complex computation. In that case we can use Composition.

From React documentation

Example without Composition.

import React from 'react';

function App() {
  const [name] = React.useState("John")
  return (
    <Child name={name}/>
  )
}

function Child(props) {
  return (
    <div>
      <p>This is a Child Component</p>
      <InnerChild {...props} />
    </div>
  )
}

function InnerChild(props) {
  return (
    <h1>Name is {props.name}</h1>
  )
}

export default App;

With Composition.

import React from 'react';

function App() {
  const [name] = React.useState("John")
  return (
    <Child>
      <p>This is a Child Component</p>
      <InnerChild>
        <h1>Name is {name}</h1>
      </InnerChild>
    </Child>
  )
}

function Child(props) {
  return (
    <>
      {props.children}
    </>
  )
}

function InnerChild(props) {
  return (
    <>
      {props.children}
    </>
  )
}

export default App;

Leave a Comment

Your email address will not be published. Required fields are marked *