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
import React from "react"; // 1. The Generic Shell Component (Containment) function CardBox({ title, children, footerActions }) { return ( <div className="border-2 rounded p-4 shadow-lg"> <h2 className="border-b pb-2 mb-2">{title}</h2> {/* This is the main composition slot */} <div className="mb-4"> {children} </div> {/* This is a custom prop slot for composition */} <div className="flex gap-2"> {footerActions} </div> </div> ); } // 2. The Specialized Component (Composing the shell) export default function WelcomeDialog() { return ( <CardBox title="Welcome aboard!" footerActions={ <> <button className="bg-blue-500 text-white px-2 rounded">Accept</button> <button className="text-gray-500">Cancel</button> </> } > {/* Everything here is passed as the implicit `children` prop */} <p>Thank you for signing up for our service.</p> <p>Please review the terms below.</p> </CardBox> ); }
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?