0
0
NextJSframework~8 mins

Composition vs inheritance in NextJS - Performance Comparison

Choose your learning style9 modes available
Performance: Composition vs inheritance
MEDIUM IMPACT
This concept affects how components are structured and rendered, impacting bundle size, rendering speed, and update efficiency.
Building reusable UI components in Next.js
NextJS
function Button({ label, children }) {
  return <button>{children || label}</button>;
}

function IconButton(props) {
  return <Button {...props}><Icon />{props.label}</Button>;
}
Composition keeps components flat and focused, enabling React to optimize rendering and tree shaking to reduce bundle size.
📈 Performance Gainsingle reflow per render, smaller bundle size, faster interaction response
Building reusable UI components in Next.js
NextJS
class Button extends React.Component {
  render() {
    return <button>{this.props.label}</button>;
  }
}

class IconButton extends Button {
  render() {
    return <button><Icon />{this.props.label}</button>;
  }
}
Inheritance creates deep component trees and forces re-rendering of entire base classes, increasing render time and bundle size.
📉 Performance Costtriggers multiple reflows per inheritance level, adds extra JS to bundle, blocks rendering longer
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Inheritance with deep class hierarchyHigh due to nested componentsMultiple reflows per inheritance levelHigher paint cost due to complex tree[X] Bad
Composition with functional componentsLower, flat component treeSingle reflow per updateLower paint cost with optimized updates[OK] Good
Rendering Pipeline
Composition allows React to efficiently reconcile component trees by minimizing unnecessary updates, while inheritance can cause larger component trees and more complex reconciliation.
JavaScript Parsing
Component Rendering
Reconciliation
Paint
⚠️ BottleneckComponent Rendering and Reconciliation
Core Web Vital Affected
INP
This concept affects how components are structured and rendered, impacting bundle size, rendering speed, and update efficiency.
Optimization Tips
1Use composition to keep component trees shallow and manageable.
2Avoid deep inheritance hierarchies to reduce reflows and rendering cost.
3Favor functional components with composition for better bundle size and update speed.
Performance Quiz - 3 Questions
Test your performance knowledge
Which pattern generally leads to smaller bundle sizes and faster rendering in Next.js?
AComposition with functional components
BDeep inheritance hierarchies
CUsing class components with inheritance
DMixing both inheritance and composition equally
DevTools: Performance
How to check: Record a performance profile while interacting with components; look for long scripting and rendering tasks caused by deep component trees.
What to look for: Look for long React reconciliation phases and multiple reflows indicating inefficient component structure.