Course contentsShow
← React
Lesson 15 of 2,3961. Why React ExistsFree lesson

Composition Over Inheritance

See why React favors composing components together rather than using classical inheritance hierarchies.

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 Card component 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 Dialog component that accepts children
  • A Title component inside it
  • A ButtonGroup component inside it
  • Individual Button components 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.