Sub topic 3
Why remove Zone.js
This chapter assumes you can build standalone components, know how the default change detection model works, and have used signal and computed. It explains the reasons for going zoneless. It does not cover the setup steps, which come in a later chapter.
What you pay for with Zone.js
Zone.js gives Angular automatic change detection. At load time it patches browser APIs such as addEventListener, setTimeout, Promise.then and XMLHttpRequest. When a patched callback finishes, NgZone emits onMicrotaskEmpty, and Angular runs change detection over the component tree.
You don't have to tell Angular that anything changed. Any async task that finishes is treated as a possible change. That convenience has costs, and they fall into five groups.
Bundle size and startup
Zone.js is a runtime dependency that every user downloads, parses and runs before the app starts. It is on the order of 30 KB minified, and roughly a third of that after compression. That is small next to a large app, but it sits on the critical path. It is also pure overhead for any code that never needed implicit change detection. Patching dozens of globals at startup adds a small amount of work to every page load.
The build also changes your code to suit Zone.js (see "Language features Zone.js cannot patch" below). Those transforms add bytes and run-time cost on top of the library itself.
Unnecessary change detection
Zone.js cannot tell whether a task changed anything. It only knows that a task ran. Each of these events can therefore trigger a full pass from the root:
- A
mousemoveorscrolllistener that only reads values. - A
setIntervalthat polls but rarely updates state. - A resolved Promise whose result you discard.
- A response from a request that didn't touch the view.
OnPush components reduce the cost of each pass, because unchanged subtrees are skipped. Angular still walks from the root and checks every OnPush boundary, and every component marked dirty is checked again. The pass itself is the cost.
The component below shows the problem. It registers a listener that never changes any state:
import { Component, HostListener } from '@angular/core';
@Component({
selector: 'app-tracker',
template: `<p>Tracking pointer</p>`,
})
export class Tracker {
@HostListener('document:mousemove', ['$event'])
onMove(event: MouseEvent) {
console.debug(event.clientX, event.clientY);
}
}In a zone-based app, every pointer move ends a patched task, and Angular runs change detection for the whole application. The usual workaround is to opt out manually with NgZone.runOutsideAngular:
import { Component, DestroyRef, NgZone, inject } from '@angular/core';
@Component({
selector: 'app-tracker',
template: `<p>Tracking pointer</p>`,
})
export class Tracker {
constructor() {
const zone = inject(NgZone);
const destroyRef = inject(DestroyRef);
const onMove = (event: MouseEvent) => {
console.debug(event.clientX, event.clientY);
};
zone.runOutsideAngular(() => {
document.addEventListener('mousemove', onMove);
});
destroyRef.onDestroy(() => {
document.removeEventListener('mousemove', onMove);
});
}
}This works, but you must remember to do it for each listener, timer and library call. Zoneless inverts the default. Angular checks only after an explicit notification, so the first version of this component costs nothing.
Language features Zone.js cannot patch
Zone.js works by replacing functions. Native async/await is syntax, not a function, so there is nothing to replace. Zone.js cannot track the continuation after an await. To keep zone-based apps working, the Angular CLI compiles async/await down to Promise-based code (generators and Promise calls). Zone.js can patch those.
The consequences:
- Your output is larger and slower than native
async/await. - Modern JavaScript output is not what the browser runs, even when you target current browsers.
- Zone-aware code needs
Promiseto be the patchedZoneAwarePromise. Anything that captures the native one early can slip past the zone.
Without Zone.js, the CLI can leave async/await untouched, because Angular no longer relies on intercepting it.
Debugging and stack traces
Zone.js wraps every patched callback. Stack traces from async code gain extra frames from zone.js, and the call stack is harder to follow in the debugger. Zone.js adds its own Zone frames, such as ZoneDelegate.invokeTask, between your code and the browser's. Stepping through a setTimeout callback includes those wrappers.
Behavior can also differ between environments. Code that runs in a zone in one place and outside it in another can trigger change detection in one and not in the other. This is a common source of bugs such as "it works when I click, but not from the websocket handler".
Interoperability and ecosystem fit
Zone.js has to patch each browser API explicitly. Newer APIs may not be patched at all, or need an optional plugin package. Callbacks from unpatched APIs run, but they don't schedule change detection, so the view stays stale until something else triggers it. Libraries that bundle their own async handling have the same problem.
Zone.js also makes Angular harder to embed. A micro-frontend host, a web component shell or a non-Angular page may have its own idea of async scheduling. Two frameworks patching the same globals can interfere. Without Zone.js, an Angular app does not modify global objects on load.
The trade: explicit notifications
Removing Zone.js changes how Angular learns about updates. Instead of "any async task may have changed something", Angular acts only when told. The main sources of notifications are:
- Signals read in templates that change value.
- Template event listeners, such as
(click). - Calls to
markForCheck(), and theasyncpipe, which calls it for you. - Creating or removing a component, or attaching a view.
Later chapters cover each of these in detail. This chapter only needs the idea that change detection becomes pay-as-you-go.
Comparing the two models
| Concern | With Zone.js | Zoneless |
|---|---|---|
| Trigger for change detection | Any patched async task finishing | Signals, template events, `markForCheck`, view attach/detach |
| Extra runtime code | Zone.js loaded and patching globals | None |
| `async`/`await` | Compiled down to Promises | Can stay native |
| Stack traces | Include Zone.js frames | Plain browser frames |
| Unrelated async work | Causes change detection | Causes none |
| Plain mutable fields | Usually update the view | Don't update the view unless notified |
| Third-party code | Works if its APIs are patched | Works if it notifies Angular itself |
The last two rows are the price. A zoneless app is only as correct as its notifications. A component that mutates a plain field inside a setTimeout worked before and silently stops updating. That is why OnPush and signals are the foundation of the next chapters.
When the case is weaker
Zoneless is not an automatic win for every app:
- A small app with cheap change detection gains little runtime performance. The benefits are mostly bundle size and clearer debugging.
- A large app that relies on implicit updates and on libraries that mutate state needs real migration work. The work can be done in steps, but it isn't free.
- A dependency that cannot notify Angular on its own may force wrappers or a delay.
The decision turns on how much of your code already uses signals, OnPush and the async pipe. The more of it that does, the cheaper the move.
Summary of the reasons
- Smaller start-up cost: no Zone.js download, parse or global patching.
- Fewer change detection passes, because only explicit notifications schedule them.
- Native
async/awaitcan ship without being compiled down. - Cleaner stack traces and more predictable behavior across environments.
- No dependence on patches for each browser API, and better embedding in other pages and frameworks.
Exercise
A zone-based app has a setInterval that polls a server every second and updates a signal only when the data changes. Describe what happens on each tick with Zone.js, and what changes in a zoneless app.
Show answer
With Zone.js, every tick ends a patched timer task, so Angular runs change detection over the whole tree each second, even when the data didn't change and no signal was set. In a zoneless app, the tick runs without any check. Change detection is scheduled only when the signal's value changes and the template reads it. Ticks that change nothing cost nothing.
Exercise
Why does Zone.js force the Angular CLI to compile native async/await into Promise-based code, and what does zoneless mode let you do instead?
Show answer
Zone.js works by replacing functions such as Promise.prototype.then. async/await is language syntax, so there is no function to replace, and Zone.js can't see the continuation after an await. The CLI therefore compiles it down to patchable Promise code, which is larger and slower. Without Zone.js, there is nothing to patch, so native async/await can be left as is.
Exercise
A component sets this.status = 'done' (a plain field) inside a setTimeout. It updated the view in a zone-based app. Why might it stop updating in a zoneless app, and name two ways to fix it.
Show answer
Zone.js used to end the timer task and trigger change detection. Without it, nothing tells Angular the field changed, so the view stays stale. Fix it by storing the state in a signal that the template reads, or by calling markForCheck() on the component's ChangeDetectorRef after changing the field.