Angular offers a hidden gem: ChangeDetectionStrategy.OnPush
. This strategy allows Angular to skip change detection for components unless specific conditions are met, drastically improving app performance. However, itβs underutilized, even though it can work wonders in dynamic UIs.
π§ How Does ChangeDetectionStrategy.OnPush
Work?
In Angular, the default change detection strategy (ChangeDetectionStrategy.Default
) checks all components in the tree for changes β even if nothing has changed! This is fine for small apps, but for large apps, it kills performance.
With OnPush
, Angular will only check a component if:
- Input properties change.
- Events (like clicks or user input) trigger updates.
- Observable subscriptions change.
β
Example:
@Component({
selector: 'app-item',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>{{ item.name }}</p>`
})
export class ItemComponent {
@Input() item!: { name: string };
}
π Whatβs Happening?
Angular will only check this component when one of the above triggers occurs, making it more performant.
This prevents Angular from checking components unnecessarily.
π§ Why You Should Use It
Boosts Performance: It reduces the amount of work Angular has to do, especially in complex or large apps.
Improved Control: You can precisely control when Angular should check your component for changes.
Low CPU Usage: Great for reducing CPU cycles when you have lots of components or a dynamic UI.
Works Best with Immutable Data: If you're using an immutable data model (e.g., NgRx, Redux), Angular can detect changes quickly when references change.
π― How to Use It Effectively
To get the most out of OnPush, use immutable data structures. Angular relies on reference checks, so if the reference to an object doesn't change, it wonβt trigger a re-render.
If you're doing manual data updates outside Angular's knowledge (like through setTimeout or WebSocket updates), use ChangeDetectorRef.detectChanges() to manually trigger change detection.
π§© Bonus: Mix OnPush with Default
You can even combine both strategies in the same app to optimize performance:
@Component({
selector: 'app-list',
template: `
<app-item *ngFor="let item of items" [item]="item"></app-item>
`,
changeDetection: ChangeDetectionStrategy.Default
})
export class ListComponent {
items = [{ name: 'Apple' }, { name: 'Banana' }];
}
In this case, ListComponent uses the default change detection strategy, but each ItemComponent uses OnPush to optimize performance further.
π Summary
ChangeDetectionStrategy.OnPush is one of the best-kept secrets for improving Angular app performance.
It limits unnecessary checks, making your app faster and more efficient.
It works well when you use immutable data patterns and can be easily mixed with other strategies.
Use it to make your Angular apps blazing fast!
Top comments (0)