Performance: Composition vs inheritance
This concept affects how components are structured and rendered, impacting bundle size, rendering speed, and update efficiency.
function Button({ label, children }) { return <button>{children || label}</button>; } function IconButton(props) { return <Button {...props}><Icon />{props.label}</Button>; }
class Button extends React.Component { render() { return <button>{this.props.label}</button>; } } class IconButton extends Button { render() { return <button><Icon />{this.props.label}</button>; } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Inheritance with deep class hierarchy | High due to nested components | Multiple reflows per inheritance level | Higher paint cost due to complex tree | [X] Bad |
| Composition with functional components | Lower, flat component tree | Single reflow per update | Lower paint cost with optimized updates | [OK] Good |
composition over inheritance when building components?function Parent() { return <Child></Child>; } correctly uses <Child></Child> tags, which is valid JSX. function Parent() { return <Child>; } uses opening tag but missing closing tag. class Parent extends Child {} uses inheritance syntax, not composition. function Parent() { return Child(); } calls Child as a function, which is not standard JSX.function Button({ label }) {
return <button>{label}</button>;
}
function Toolbar() {
return <div><Button label="Save" /></div>;
}class BaseButton extends React.Component {
render() {
return <button>Base</button>;
}
}
function SubmitButton() {
return <BaseButton label="Submit" />;
}function Card({ children }) {
return <div className="card">{children}</div>;
}
function Profile() {
return (
<Card>
<h2>User Name</h2>
<p>User details here</p>
</Card>
);
}Pass the test and this pattern moves unknown