Composition Over Inheritance
What you'll learn: Why React encourages building UIs by combining simple components rather than creating complex inheritance chains.
The Core Idea
In traditional object-oriented programming, you might create a hierarchy of classes where Button extends BaseComponent, IconButton extends Button, and so on. React takes a different approach: instead of inheriting behavior, you compose components by nesting and combining them like building blocks.
Think of inheritance like a family tree—each generation inherits traits from parents, creating rigid relationships. Composition is more like LEGO bricks—you snap together whatever pieces you need for each specific creation.
Why Composition Wins in React
Remember Component-Based Architecture? Each component is meant to be a reusable, independent piece. When you use inheritance, you create tight coupling—changing a parent class affects all children. This violates the independence we want.
With composition, you build complex UIs by combining simple components:
- A
Cardcomponent doesn't inherit from anything - Instead, it accepts other components as children
- You can put anything inside: text, images, buttons, other cards
- Each piece remains independent and reusable
Composition in Practice (Conceptually)
Imagine you need a dialog box with a title and buttons. Instead of creating DialogWithButtons extends BaseDialog, you compose:
- A
Dialogcomponent that accepts children - A
Titlecomponent inside it - A
ButtonGroupcomponent inside it - Individual
Buttoncomponents inside that
Each component does one thing well. You arrange them together, following Unidirectional Data Flow to pass data down as needed.
Key Takeaway: React favors composing small, focused components together over building inheritance hierarchies—this keeps components flexible, reusable, and easier to understand.