What is Component Composition?
You'll learn: How to build complex UIs by combining simple, reusable components together like building blocks.
The Core Idea
Component composition is React's fundamental design pattern: instead of building one giant, complicated component, you create small, focused components and compose them together to create something more sophisticated.
Think of it like building with LEGO bricks. You don't have one massive brick that forms an entire castle. Instead, you have many small, simple bricks that you snap together. Each brick does one thing well, but together they create something complex and beautiful.
How It Works in Practice
You've already been doing this! When you write:
function UserProfile() {
return (
<div>
<Avatar />
<UserName />
<UserBio />
</div>
);
}
You're composing UserProfile from three smaller components. Each child component handles one responsibility: showing an avatar, displaying a name, or rendering a bio. UserProfile doesn't need to know how each child works—it just arranges them together.
This is powerful because:
- Each component stays simple and testable
- You can reuse
Avatarin other contexts - Changes to
UserBiodon't affectAvatarorUserName - Your code mirrors the visual structure of your UI
The Alternative (Don't Do This)
Without composition, you'd cram everything into one massive component with hundreds of lines handling avatars AND names AND bios all mixed together. That becomes unmaintainable fast.
Key Takeaway: Composition means building complex UIs from small, focused components that work together—it's the heart of React's component model and keeps your code organized and reusable.