Performance Optimization: OnPush by Default with Immutable Data Flows
OnPush by Default: Prevent unnecessary re-renders by pairing OnPush change detection with immutable data flows.
By default, Angular operates under the Default (CheckAlways) change detection strategy. In this mode, whenever an asynchronous event fires anywhere in the application—a network response, an interval timer, or a keystroke in an unrelated sidebar—Angular executes a top-to-bottom scan through every component in the DOM tree to check expressions for changes.
In small apps, this blanket sweep goes unnoticed. In large enterprise applications with thousands of active template bindings, it leads to dropped frames, input lag, and CPU spikes.
Setting ChangeDetectionStrategy.OnPush by default shifts Angular from a blanket scanner to a surgical updater. An OnPush component informs the framework: skip checking this component and its child subtree unless its inputs change by reference, a DOM event fires within its template, or a reactive signal emits.
## 1. Default vs. OnPush: The Visual Tree Check
[DEFAULT STRATEGY] (Top-to-Bottom Blanket Check)
App Root (Checked)
/ \
Navbar (Checked) Dashboard (Checked)
/ \ / \
Menu User UserList Analytics (Checked)
(Checked) (Checked) (Checked)
Even if only "User" was clicked, EVERY component is re-evaluated.
[ONPUSH STRATEGY] (Subtree Pruning)
App Root (Checked)
/ \
[Navbar: SKIPPED] Dashboard (Checked: Input reference changed)
/ \
[UserList: SKIPPED] Analytics (Checked: Signal updated)
Unchanged branches are pruned completely from the change detection pass.
## 2. Enforcing OnPush by Default via Angular CLI
Rather than manually appending changeDetection: ChangeDetectionStrategy.OnPush to every component decorator, configure the Angular CLI schematics in angular.json so every generated component uses OnPush automatically:
```json
{
"schematics": {
"@schematics/angular:component": {
"changeDetection": "OnPush"
}
}
}
```
Every component created via ng g c <name> now includes:
```ts
import { Component, ChangeDetectionStrategy } from '@angular/core';
@Component({
selector: 'app-user-metric',
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush, // Injected by default
template: `...`
})
export class UserMetricComponent {}
```
## 3. The Three Triggers: When Does OnPush Actually Re-render?
An OnPush component bypasses change detection passes unless at least one of these conditions occurs:
- An Input changes by Object Reference (===): Angular runs a shallow reference equality check. Changing an internal property of a mutated object fails this test and will not schedule a render.
- **A DOM Event originates within the template:** User actions bound directly in HTML (e.g., (click), (submit), (keydown)) mark the component and its ancestors dirty.
- **A reactive Signal or AsyncPipe emits:** Reading a signal() or binding an Observable via | async in the template directly notifies the framework scheduler when new data arrives.
## 4. The Golden Rule: Pairing OnPush with Immutable Data
The most common trap with OnPush is mutating state in place. Because Angular evaluates objects by memory reference, in-place property mutations are invisible to the change detector.
### The Anti-Pattern: In-Place Mutation
```ts
// ❌ WRONG: In-place object mutation
export class ParentComponent {
user = { name: 'Alex', role: 'Viewer' };
promoteUser(): void {
// Memory address remains identical!
this.user.role = 'Admin';
// Child will NOT update on screen
}
}
```
```html
Because prevUser === nextUser evaluates to true, Angular assumes the payload is unchanged and prunes the child component from the pass.
```
- **The Modern Solution:** Pure Immutable Updates
Generate fresh object and array references using object spread syntax (...), map(), or filter():
```ts
// ✅ CORRECT: Spreading creates a brand-new object reference
export class ParentComponent {
user = signal({ name: 'Alex', role: 'Viewer' });
items = signal(['TypeScript', 'Angular']);
promoteUser(): void {
// 1. Immutable object update
this.user.update(u => ({ ...u, role: 'Admin' }));
}
// 2. Immutable array insertion
addItem(item: string): void {
this.items.update(list => [...list, item]); // New array reference
}
// 3. Immutable array deletion
removeItem(target: string): void {
this.items.update(list => list.filter(i => i !== target)); // New array reference
}
}
```
## 5. Modern Component Architecture: Signals + OnPush
Combining OnPush with Angular Signals produces the leanest possible runtime profile: unnecessary subtree traversals are pruned, while fine-grained dirty nodes are scheduled cleanly without manual ceremony.
```ts
// src/app/features/analytics/realtime-kpi.component.ts
import { Component, ChangeDetectionStrategy, input, computed } from '@angular/core';
import { CurrencyPipe } from '@angular/common';
export interface KpiData {
id: string;
label: string;
revenue: number;
expenses: number;
}
@Component({
selector: 'app-realtime-kpi',
standalone: true,
imports: [CurrencyPipe],
changeDetection: ChangeDetectionStrategy.OnPush, // 1. Enforce OnPush
template: `
`
})
export class RealtimeKpiComponent {
// 2. Input Signal: Reference identity tracked automatically
kpi = input.required();
// 3. Computed Signal: Pure, auto-memoized derivation
netProfit = computed(() => this.kpi().revenue - this.kpi().expenses);
refreshLocalSnapshot(): void {
console.log('Local refresh requested for KPI:', this.kpi().id);
}
}
```
## 6. Edge Cases: Working with External Asynchronous Services
When consuming non-Angular SDKs, WebSockets, or third-party event emitters that run outside the framework, Angular won't automatically detect state changes in an OnPush tree.
- **Pattern A:** Convert Streams to Signals (toSignal)
The cleanest modern pattern is wrapping RxJS streams with toSignal() from @angular/core/rxjs-interop. It manages cleanup and marks the view dirty on every emission:
```ts
import { Component, ChangeDetectionStrategy, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { LiveMarketService } from '../services/live-market.service';
@Component({
selector: 'app-stock-ticker',
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
{{ kpi().label }}
Revenue: {{ kpi().revenue | currency }}
Expenses: {{ kpi().expenses | currency }}
Net Margin: {{ netProfit() | currency }}
Price: {{ currentPrice() ?? 'Connecting...' }}
`
})
export class StockTickerComponent {
private marketService = inject(LiveMarketService);
// toSignal handles internal markForCheck notifications on every emit
currentPrice = toSignal(this.marketService.priceStream$);
}
```
- **Pattern B:** Explicit Notification (ChangeDetectorRef.markForCheck)
When bridging raw callbacks from external JavaScript SDKs (e.g., WebRTC, native canvas loops, payment sheets):
```ts
import { Component, ChangeDetectionStrategy, ChangeDetectorRef, inject, OnInit } from '@angular/core';
import { ExternalTelemetryClient } from 'telemetry-sdk';
@Component({
selector: 'app-device-monitor',
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
template: `Ping: {{ latency }}ms
`
})
export class DeviceMonitorComponent implements OnInit {
private cdr = inject(ChangeDetectorRef);
latency = 0;
ngOnInit(): void {
ExternalTelemetryClient.onPing((ms: number) => {
this.latency = ms;
// Explicitly queue this OnPush component for the next render cycle
this.cdr.markForCheck();
});
}
}
```
## 7. Performance Impact: Default vs. OnPush
| Metric | Default (CheckAlways) | OnPush + Immutable Signals | Component checks per event | Every component in the application (N) |
| --- | --- | --- | --- | --- |
| Only branches with changed references or active signals | CPU load during high-frequency events | High (triggers on window scroll, pointermove, intervals) | Low (unrelated trees are pruned immediately) | State Predictability |
| High risk of unintended in-place mutations | Enforces strict, traceable reference boundaries | Zoneless Readiness | Hard to decouple from Zone.js monkey patching | Ideal architectural foundation for complete Zoneless execution |