Home
React
Patterns: Composition
Daniel Nguyen
Daniel Nguyen
July 20, 2025
1 min

Use component composition to avoid passing props through components that don’t need them. It makes your code cleaner, more reusable, and easier to maintain.

1. Problem: Prop Drilling

Prop drilling happens when data passes through intermediate components that don’t use it.

function App() {
const [count, setCount] = useState(0);
return (
<Child
count={count}
increment={() => setCount(c => c + 1)}
/>
);
}
function Child({ count, increment }) {
return (
<GrandChild
count={count}
increment={increment}
/>
);
}
function GrandChild({ count, increment }) {
return <button onClick={increment}>{count}</button>;
}

Child only forwards props to GrandChild. It doesn’t need to know about the counter.

2. Solution: Component Composition

Instead of passing data through every layer, pass a React element using children.

function App() {
const [count, setCount] = useState(0);
return (
<Child>
<GrandChild
count={count}
onIncrement={() => setCount(c => c + 1)}
/>
</Child>
);
}
function Child({ children }) {
return <div className="container">{children}</div>;
}
function GrandChild({ count, onIncrement }) {
return (
<button onClick={onIncrement}>
{count}
</button>
);
}

Now, Child doesn’t need to know about count or onIncrement. It simply renders its children.

3. Why Does This Work?

  • Less prop drilling: Intermediate components don’t forward unnecessary props.
  • Better reusability: Child can render different content without knowing its implementation.
  • Clearer responsibilities: App manages state, Child handles layout, and GrandChild handles interaction.

4. When Should You Use It?

Use composition for layout components, wrappers, modals, and deeply nested UI where intermediate components don’t need access to the data.


Tags

#ReactPatterns

Share

Daniel Nguyen

Daniel Nguyen

Frontend Developer

Frontend developer specializing in React, Next.js, and JavaScript. Writing practical guides on modern web development at Dev98.

Expertise

React
Next.js
JavaScript
TypeScript
Python

Social Media

githublinkedinyoutubewebsite

Related Posts

Advanced React Patterns
Patterns: Latest Ref
July 23, 2025
1 min
Dev98

Dev98

React · Next.js · Web development