0
0
Angularframework~8 mins

When to use OnPush in Angular - Performance & Optimization

Choose your learning style9 modes available
Performance: When to use OnPush
HIGH IMPACT
OnPush affects how Angular detects changes and updates the DOM, impacting rendering speed and responsiveness.
Optimizing change detection for a component with mostly immutable inputs
Angular
import { Component, ChangeDetectionStrategy, Input } from '@angular/core';
@Component({
  selector: 'app-good',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `<p>{{data.name}}</p>`
})
export class GoodComponent {
  @Input() data!: { name: string };
}
OnPush runs change detection only when input references change, reducing unnecessary checks.
📈 Performance Gainreduces change detection cycles, improving input responsiveness and lowering reflows
Optimizing change detection for a component with mostly immutable inputs
Angular
import { Component } from '@angular/core';
@Component({
  selector: 'app-bad',
  template: `<p>{{data.name}}</p>`
})
export class BadComponent {
  data = { name: 'Angular' };
}
Default change detection runs on every event and async operation, causing many unnecessary DOM checks.
📉 Performance Costtriggers change detection on every event, causing multiple reflows and slower INP
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Default Change DetectionRuns on all events and async tasksMultiple reflows per eventHigher paint cost due to frequent updates[X] Bad
OnPush Change DetectionRuns only on input reference changes or eventsMinimal reflowsLower paint cost with fewer updates[OK] Good
Rendering Pipeline
OnPush changes when Angular runs change detection, reducing the frequency of style recalculations and layout updates.
Change Detection
Layout
Paint
⚠️ BottleneckChange Detection stage is most expensive when running frequently on many components.
Core Web Vital Affected
INP
OnPush affects how Angular detects changes and updates the DOM, impacting rendering speed and responsiveness.
Optimization Tips
1Use OnPush for components with immutable inputs to reduce change detection frequency.
2Avoid OnPush if your component relies on mutable objects that change internally without new references.
3OnPush improves input responsiveness by minimizing unnecessary DOM updates.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of using OnPush change detection in Angular?
AIt disables change detection completely.
BIt reduces unnecessary change detection cycles by running only on input changes.
CIt forces Angular to check all components more frequently.
DIt increases bundle size to improve speed.
DevTools: Performance
How to check: Record a performance profile while interacting with the component. Look for change detection cycles and layout recalculations.
What to look for: Fewer and shorter change detection events and layout recalculations indicate better performance with OnPush.