Specialization Through Composition
What you'll learn: How to create specialized components by wrapping and configuring general-purpose components, rather than duplicating code.
The Core Idea
Imagine you have a general-purpose Button component. Instead of creating entirely separate components for every button type in your app, you can compose specialized versions by wrapping that base component with specific props and logic.
This is specialization through composition: taking a generic, reusable component and creating more specific versions by configuring it with predetermined values.
// General-purpose Button
function Button({ label, color, onClick }) {
return <button style={{ color }} onClick={onClick}>{label}</button>;
}
// Specialized through composition
function DangerButton({ label, onClick }) {
return <Button label={label} color="red" onClick={onClick} />;
}
function SuccessButton({ label, onClick }) {
return <Button label={label} color="green" onClick={onClick} />;
}
Notice how DangerButton and SuccessButton don't rewrite button logic—they compose the base Button with specific configurations. They're specialized versions that lock in certain behaviors (the color) while still accepting other props (label, onClick).
When to Use This Pattern
Use specialization when you find yourself repeatedly passing the same props to a component. Instead of writing <Button color="red" /> everywhere, create a DangerButton that encapsulates that decision.
This keeps your code DRY (Don't Repeat Yourself) and makes changes easier. Need all danger buttons to be bold? Change it once in DangerButton, not in fifty places.
Real-World Analogy
Think of a sandwich shop: they have a general "custom sandwich" option, but also specialized menu items like "The Italian" or "Turkey Club." Those specials are just the custom sandwich with predetermined ingredients—composition with configuration baked in.
Key Takeaway: Specialization through composition means creating purpose-built components by wrapping general ones with preset configurations, reducing duplication and centralizing decisions.