- Home
- /
- Tutorials
- /
- React Tutorial
- /
- Component Patterns
Custom Hooks and Patterns
Component Patterns
A component that takes fourteen props is not configurable. It is several components that have not been separated yet.
Composition over configuration
The instinct when a component needs a variation is to add a prop. Do that a few times and you have a component with a dozen booleans and a body full of conditionals.
The alternative is to accept content rather than options - let the caller pass what goes inside, and keep the component responsible only for structure.
Options versus slots
jsx
// Configuration: every variation needs a new prop.
function ConfiguredCard({ title, showBadge, badgeText, showFooter, footerText }) {
return (
<div style={{ border: "1px solid #cbd5e1", padding: 10, borderRadius: 8 }}>
<b>{title}</b> {showBadge && <span>[{badgeText}]</span>}
{showFooter && <p style={{ color: "#64748b" }}>{footerText}</p>}
</div>
)
}
// Composition: one prop, unlimited variations.
function Card({ children }) {
return (
<div style={{ border: "1px solid #cbd5e1", padding: 10, borderRadius: 8 }}>
{children}
</div>
)
}
const root = ReactDOM.createRoot(document.getElementById("root"))
root.render(
<div style={{ display: "grid", gap: 10 }}>
<ConfiguredCard title="Configured" showBadge badgeText="new" showFooter footerText="a footer" />
<Card>
<b>Composed</b> <span>[new]</span>
<p style={{ color: "#64748b" }}>Anything at all goes here.</p>
</Card>
</div>
)