React Course
React
/
Intermediate

Composition vs Inheritance

Definition

Composition is the React paradigm of building complex components by combining smaller, simpler components, usually via the `children` prop. React heavily favors Composition over Object-Oriented Inheritance.

Explain Like I'm New

Inheritance is like biology: A Dog IS A Mammal. It inherits traits from its parent. Composition is like Legos: A Car HAS A Wheel, HAS An Engine, HAS A Door. React says, "Don't try to make a SpecialButton class that inherits from a GenericButton class. Just build a GenericButton, and compose it by passing different icons and text inside it as children."

Real World Example

Building a Modal. Instead of creating an `AlertModal` that inherits from `BaseModal`, you create a generic `<Modal>` component that accepts `children`. Then you build `<AlertModal>` by returning `<Modal><h1>Alert!</h1></Modal>`.

Common Use Cases

  • •Creating highly reusable UI shells (Cards, Modals, Layouts)
  • •Avoiding the "Gorilla Banana" problem of OOP (where you ask for a banana but get a gorilla holding the banana and the entire jungle)

Interactive Example

Loading Code Playground...

Interview Questions

basic

  • What is the `children` prop?
  • Does React recommend Inheritance or Composition?

intermediate

  • How do you pass multiple "slots" of children to a component? (e.g., a header and a footer)
  • What does "Containment" mean in the context of Composition?

advanced

  • What is the `React.Children` API used for?
  • Why did React abandon mixins?

trick

  • Can a child component access or modify its own `children` prop?

Flash Cards

Question

How do you pass multiple slots of children?

Click to reveal answer
Answer

You can pass React elements as custom props! Instead of just using the default `children`, you can pass `<Layout leftSidebar={<Sidebar />} rightContent={<Main />} />`.

Question

Can a component modify its own children prop?

Click to reveal answer
Answer

Props are read-only, so you cannot mutate `children` directly. However, using the advanced `React.cloneElement` and `React.Children.map` APIs, a parent CAN clone its children and inject new props into them before rendering.

Question

Why did React abandon Mixins (Inheritance)?

Click to reveal answer
Answer

Mixins caused implicit dependencies, name clashes, and snowballing complexity. Composition makes data flow explicit and visible.