Sub topic 5
Running side effects with effect()
This chapter assumes you know basic TypeScript, Angular components and dependency injection, and how signal() and computed() work. Change detection only needs to be familiar at a high level.
What an effect is
An effect is a function that Angular runs for you, once at first and again whenever a signal it read has changed. A computed signal produces a value. An effect produces no value. It reaches outside the signal graph to do something, such as logging, writing to localStorage, calling a third-party library, or drawing on a canvas.
import { Component, signal, computed, effect } from '@angular/core';
@Component({
selector: 'app-counter',
template: `<button (click)="increment()">{{ count() }} (x2 = {{ doubled() }})</button>`,
})
export class CounterComponent {
count = signal(0);
doubled = computed(() => this.count() * 2);
constructor() {
effect(() => {
console.log(`count=${this.count()}, doubled=${this.doubled()}`);
});
}
increment() {
this.count.update((c) => c + 1);
}
}The effect reads count() and doubled() while it runs. Angular records both as dependencies. After each click the effect runs again. You do not subscribe or unsubscribe by hand.
When an effect runs
Three rules describe the timing.
- An effect always runs at least once. It does not run at the moment you call
effect(). Angular schedules the first run, and for a component effect that happens during change detection. - After that, it runs only when a dependency has changed. Setting a signal to a value it already holds (compared with
Object.isby default) does not count as a change. - Runs are batched. If you call
count.set(1),count.set(2)andcount.set(3)in the same synchronous block, the effect runs once and sees3.
Because of rule 3, you cannot use an effect to observe every intermediate value. If you need each value, handle the event that produced it.
Dependencies are what the last run read
Effects use the same dynamic tracking as computed signals. Only signals read during the most recent run are dependencies. If a read sits inside an if branch that was not taken, a change to that signal does not re-run the effect.
Where you can create an effect
effect() needs an injection context, because Angular ties the effect's lifetime to the component, directive or service that owns it. These places work:
- A constructor.
- A field initializer, such as
private logger = effect(() => { ... });. - Any function run through
runInInjectionContext.
Calling effect() inside a click handler throws an error, because no injection context is active there. If you must create an effect later, inject Injector and pass it as an option: effect(() => { ... }, { injector: this.injector }).
The effect is destroyed automatically with its owner. The next chapter covers cleanup in more detail.
Writing signals inside an effect
Recent Angular versions let an effect set other signals. Older versions required the allowSignalWrites option, so check your version. Even when allowed, this is a warning sign. If an effect reads signal A only to compute and set signal B, B should be a computed() or a linkedSignal(). Effects that chain into other effects are hard to follow and can trigger extra change detection passes.
Common errors
| Symptom | Likely cause |
|---|---|
| `NG0203` error about injection context | `effect()` was called outside a constructor, field initializer or injection context |
| Effect never re-runs | It reads no signals, or the read happens in a branch that was skipped on the last run |
| Effect runs one time too few | Several synchronous writes were batched into one run |
| Effect runs too often | It reads signals you meant to ignore, which is the job of `untracked()` |
| Infinite loop of runs | The effect reads a signal and also writes to it |
Check your understanding
Exercise
A component has a = signal(1) and an effect that logs this.a(). In a click handler you run this.a.set(2); this.a.set(3); this.a.set(3);. How many times does the effect run because of this click, and what does it log?
Show answer
It runs once and logs 3. The effect is scheduled to run later during change detection, not at each set call, so it sees only the final value. The last set(3) would not have counted as a change anyway, because the value was already 3.
Exercise
Why does this code throw, and how can you fix it? save() { effect(() => localStorage.setItem('n', String(this.n()))); }
Show answer
save() is called from outside an injection context, so effect() cannot find the owner whose lifetime it should follow. Create the effect in the constructor or a field initializer. If it must be created later, inject Injector and pass { injector: this.injector } as the effect option.