Concept Flow - Composition vs inheritance
Start
Choose approach
Use Inheritance
Extend base class
Override or add
Use in app
End
Shows the decision flow between using inheritance or composition in Next.js components.
function Button(props) { return <button>{props.label}</button>; } function IconButton(props) { return <Button label={props.label} />; }
| Step | Component Rendered | Props Passed | Output Rendered | Notes |
|---|---|---|---|---|
| 1 | Button | { label: 'Click me' } | <button>Click me</button> | Button renders with label from props |
| 2 | IconButton | { label: 'Click me' } | <button>Click me</button> | IconButton composes Button, passing label |
| 3 | App uses IconButton | N/A | <button>Click me</button> | IconButton used in app, renders Button inside |
| 4 | End | N/A | N/A | Rendering complete |
| Variable | Start | After IconButton Render | Final |
|---|---|---|---|
| props.label | undefined | 'Click me' | 'Click me' |
Composition vs Inheritance in Next.js: - Inheritance: Extend a base component class (rare in React/Next.js) - Composition: Build components by combining others via props/children - Composition is preferred for flexibility and reuse - Pass props to child components to customize - Avoid deep inheritance chains in React apps
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