Sub topic 12
Reducing work with OnPush and signals
This chapter assumes you can read a Performance panel trace, you know what a change detection pass looks like in it, and you have used the Angular DevTools profiler to find components that check often. The goal now is to make Angular check fewer components, and to confirm in a trace that it did.
Why default change detection does too much
With the default strategy, Angular checks every component in the tree on each change detection pass. Zone.js triggers a pass after any click, timer, or network response. Every binding in every template is re-evaluated, even in components whose data did not change.
For a small app this is fine. For a large tree, or a template that calls a function, the cost shows up in the flame chart as a wide tick call with many nested template function calls. If you see that shape after a trivial event, the tree is doing work it does not need to do.
What OnPush changes
A component with ChangeDetectionStrategy.OnPush is skipped during a pass unless one of these happens:
- One of its
input()values changes by reference (a new object or array, not a mutation). - An event handler declared in its own template runs, such as
(click). - A signal read in its template changes.
- The
asyncpipe receives a new value, ormarkForCheck()is called.
The skip applies to the component and its whole subtree, so one OnPush component near the top of a large subtree can remove a lot of work.
The table summarizes how the two strategies differ.
| Aspect | Default | OnPush |
|---|---|---|
| Checked on every pass | Yes | Only when marked dirty |
| Input mutation (`obj.x = 1`) | Seen | Not seen |
| Input replacement (`obj = {...obj, x: 1}`) | Seen | Seen |
| Cost in a large tree | Grows with tree size | Grows with changed branches |
Where the saving appears in a trace
The diagram shows how a pass visits components with and without OnPush.
In a trace, compare the same interaction before and after. The tick entry should be shorter, and the Angular DevTools profiler should show fewer components highlighted per pass.
Making OnPush work: immutable updates
The most common OnPush bug is mutating data in place. The component does not update because the input reference is the same.
import { ChangeDetectionStrategy, Component, input } from '@angular/core';
interface Task {
id: number;
title: string;
done: boolean;
}
@Component({
selector: 'app-task-list',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<ul>
@for (t of tasks(); track t.id) {
<li>{{ t.title }} @if (t.done) { (done) }</li>
}
</ul>
`,
})
export class TaskListComponent {
tasks = input.required<Task[]>();
}If a parent does this.tasks[0].done = true, this list will not refresh. The parent must produce a new array, for example this.tasks = this.tasks.map(t => t.id === 1 ? { ...t, done: true } : t). Replacing only the changed element keeps the other objects stable, which also helps row tracking.
Computed signals replace template method calls
A function called in a template runs on every pass, because Angular cannot know whether its result changed. In the flame chart this appears as the same function repeated under each component's template function.
A computed signal caches its result and recalculates only when a signal it read changes. This is the pattern from the earlier example.
import { ChangeDetectionStrategy, Component, computed, input } from '@angular/core';
@Component({
selector: 'app-order-total',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>Total: {{ total() }}</p>`,
})
export class OrderTotalComponent {
items = input.required<{ price: number; qty: number }[]>();
total = computed(() =>
this.items().reduce((sum, i) => sum + i.price * i.qty, 0)
);
}Reading total() in the template is cheap when nothing changed, since it returns the stored value. The reduce runs again only when items receives a new array.
Signals as local state
Signals also work for state that the component owns. When a signal read in a template changes, Angular marks only that component for checking, even under OnPush.
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
@Component({
selector: 'app-counter',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<button (click)="increment()">Clicked {{ count() }} times</button>
`,
})
export class CounterComponent {
count = signal(0);
increment() {
this.count.update(n => n + 1);
}
}This is why signals pair well with OnPush: updating count refreshes this component without relying on its parent being checked.
Common mistakes
- Putting OnPush on leaf components only. The saving comes from skipping subtrees, so apply it high enough to cover large branches, such as list containers and page sections.
- Using a computed signal for a cheap expression. Interpolating
{{ a() + b() }}costs almost nothing. Reservecomputedfor loops, sorting, filtering, and formatting of large data. - Writing to signals inside
computed. A computed value must be a pure function of other signals. Side effects belong in event handlers oreffect. - Assuming OnPush fixes slow code. If the checked component is expensive to render, OnPush only makes it run less often. Profile to see whether the remaining cost is in a single heavy template.
- Mutating arrays held in signals.
items().push(x)does not notify readers. Useitems.update(list => [...list, x]).
Confirming the change helped
Follow the same procedure as for any optimization:
- Record the interaction in a production-like build with the same CPU throttling, and note the duration of the
ticktask. - Make one change, such as adding OnPush to a list container.
- Record the same interaction again, several times, and compare medians.
- In Angular DevTools, check that fewer components are highlighted per pass.
- Check behavior: confirm the view still updates after every kind of data change.
A faster trace with a stale view is a bug, not a gain.
Exercise
A parent component holds rows and runs this.rows[2].selected = true when the user clicks. The child <app-grid [rows]="rows"> uses OnPush and does not show the selection. Why, and what is the fix that keeps the OnPush saving?
Show answer
The mutation keeps the same array and object references, so the OnPush child sees no input change and is skipped. Replace the data instead of mutating it, for example this.rows = this.rows.map((r, i) => i === 2 ? { ...r, selected: true } : r). The child then receives a new array reference and is checked, while other OnPush components with unchanged inputs are still skipped.
Exercise
A template shows {{ visibleTotal() }}, where visibleTotal is a method that filters 5,000 items and sums them. In the flame chart it appears many times per click. How do you change it, and what should you see in the next trace?
Show answer
Make the items an input or signal and define visibleTotal = computed(() => ...) reading them, in an OnPush component. In the next trace the filter and sum should run only when the items change. They should no longer appear on every pass, and the tick duration should drop.