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
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?