Sub topic 4
Running Side Effects with effect()
This chapter assumes you can already create writable signals with signal(), update them with set() and update(), and derive values with computed(). It also assumes you know what Angular dependency injection is and where a constructor runs in a component's life.
A computed() signal turns signals into a new value. Some reactive code needs to do work outside the signal graph when a signal changes. It might write to localStorage, send an analytics event, log a message, or call a third-party chart library. effect() handles that case. An effect is a function that Angular runs once, records which signals it read, and runs again whenever any of those signals change.
The working model
An effect is a consumer in the signal graph, like a computed(). There are two differences:
- A computed is lazy. It only evaluates when something reads it. An effect is eager: Angular schedules it to run whether or not anyone is "reading" anything.
- A computed returns a value. An effect returns nothing useful. Its whole purpose is its side effect.
Here is the smallest useful example. It saves the theme to localStorage every time the theme changes:
import { Component, effect, signal } from '@angular/core';
@Component({
selector: 'app-theme',
template: `<button (click)="toggle()">Theme: {{ theme() }}</button>`,
})
export class ThemeComponent {
theme = signal<'light' | 'dark'>('light');
constructor() {
effect(() => {
localStorage.setItem('theme', this.theme());
});
}
toggle() {
this.theme.update(t => (t === 'light' ? 'dark' : 'light'));
}
}During its first run the effect reads this.theme(), so Angular records theme as a dependency. When toggle() changes the signal, Angular marks the effect as dirty and schedules it to run again.
Dependencies are dynamic
An effect tracks only the signals it read during its most recent run. If a branch skips a signal, that signal is not a dependency until a later run reads it:
import { Component, effect, signal } from '@angular/core';
@Component({ selector: 'app-debug-log', template: '' })
export class DebugLogComponent {
debug = signal(false);
count = signal(0);
constructor() {
effect(() => {
if (this.debug()) {
console.log('count is', this.count());
}
});
}
}While debug() is false, changing count does not re-run the effect, because the last run never read count. Once debug becomes true, the next run reads count and starts tracking it. This is usually what you want. It also explains a common surprise: an effect that "ignores" a signal often read it only inside a branch that didn't execute.
When effects run
Effects do not run synchronously when you call set(). Angular schedules them and runs them during its next change detection pass. This has two consequences.
First, an effect always runs at least once, shortly after it is created. It does not run inside the constructor call itself.
Second, several synchronous writes collapse into one run:
this.count.set(1);
this.count.set(2);
this.count.set(3);
// The effect runs once and sees 3. It never sees 1 or 2.An effect reacts to the current state. It does not receive a log of every change. If you need every intermediate value, such as for an undo history, record it where the write happens, or model the changes as an Observable stream.
Angular separates two kinds of effects:
| Kind | Where it is created | When it runs | Destroyed when |
|---|---|---|---|
| Component effect | A component or directive's injection context | During change detection, before that component's view is checked | The component or directive is destroyed |
| Root effect | A root-level service or other non-component context | During change detection, before any component is checked | The application is destroyed, or you call `destroy()` |
Neither kind runs at a reliable point for reading the rendered DOM. If you need to measure or change DOM elements after Angular has rendered, use afterRenderEffect() or afterNextRender(). A later chapter on signal queries shows afterNextRender() in use.
The injection context requirement
effect() needs an injection context. That is a point in your code where inject() works, such as a constructor, a field initializer, or a factory function. Angular uses the context to find the DestroyRef that controls the effect's lifetime and the scheduler that runs it.
If you call effect() from a click handler or ngOnInit, Angular throws error NG0203: effect() can only be used within an injection context. You can fix it in either of two ways:
- Move the effect into the constructor or a field initializer.
- Pass an injector explicitly.
import { Component, EffectRef, Injector, effect, inject, signal } from '@angular/core';
@Component({
selector: 'app-logger',
template: `
<button (click)="count.set(count() + 1)">{{ count() }}</button>
<button (click)="start()">Start logging</button>
<button (click)="stop()">Stop logging</button>
`,
})
export class LoggerComponent {
private injector = inject(Injector);
count = signal(0);
private logRef?: EffectRef;
start() {
if (this.logRef) return;
this.logRef = effect(() => console.log('count:', this.count()), {
injector: this.injector,
});
}
stop() {
this.logRef?.destroy();
this.logRef = undefined;
}
}effect() returns an EffectRef. Calling its destroy() method stops the effect early. Without destroy(), this effect still ends when the component is destroyed, because the injector it was given belongs to the component.
Cleaning up between runs
Many side effects create something that must be undone: a timer, a subscription, an event listener, or an in-flight request. The effect function receives an onCleanup callback. Angular runs the function you register just before the next run of the effect, and once more when the effect is destroyed.
import { Component, effect, signal } from '@angular/core';
@Component({
selector: 'app-ticker',
template: `
<p>Ticks: {{ ticks() }}</p>
<button (click)="intervalMs.set(250)">Fast</button>
<button (click)="intervalMs.set(1000)">Slow</button>
`,
})
export class TickerComponent {
intervalMs = signal(1000);
ticks = signal(0);
constructor() {
effect(onCleanup => {
const ms = this.intervalMs();
const id = setInterval(() => this.ticks.update(t => t + 1), ms);
onCleanup(() => clearInterval(id));
});
}
}When intervalMs changes, Angular clears the old interval before it starts a new one. When the component is destroyed, Angular clears the last interval. Without onCleanup, each speed change would add another interval running alongside the ones before it.
The interval callback writes to ticks, but that write happens later, outside the effect's run, so ticks is not a dependency. The effect only reads intervalMs.
Writing signals inside effects
In Angular 19 and later you can write to signals inside an effect. Earlier versions required an allowSignalWrites: true option, which no longer has any effect. Being allowed to do this does not make it a good idea. The usual mistake is to copy state from one signal to another:
// Anti-pattern: synchronizing state with an effect
firstName = signal('Ada');
lastName = signal('Lovelace');
fullName = signal('');
constructor() {
effect(() => {
this.fullName.set(`${this.firstName()} ${this.lastName()}`);
});
}This version has three problems. fullName is briefly wrong after each change, until the effect runs. It costs an extra change detection pass. And any code can call fullName.set() and break the relationship. A computed fixes all three:
fullName = computed(() => `${this.firstName()} ${this.lastName()}`);A more serious version of this mistake is an effect that reads and writes the same signal. For example, effect(() => this.count.set(this.count() + 1)) reschedules itself on every run. Angular stops the loop in development mode and reports it, but the real fix is to remove the cycle.
Use this table to decide what to reach for:
| You want to | Use |
|---|---|
| Compute a value from other signals | `computed()` |
| Keep writable state that resets when a source changes | `linkedSignal()` (covered in a later chapter) |
| Touch something outside Angular's signal graph | `effect()` |
| Read or measure the DOM after rendering | `afterRenderEffect()` or `afterNextRender()` |
| Run async pipelines with debouncing or cancellation | RxJS interop (covered in a later chapter) |
A good rule: if the effect's only job is to call set() on another signal, it should probably be a computed() or a linkedSignal().
Common errors and edge cases
- NG0203 at runtime. You called
effect()outside an injection context. Move it into the constructor, or pass{ injector }. - The effect never re-runs. The signal was read only inside a branch that didn't run, or inside a callback such as
setTimeoutor a promise'sthen. Only reads that happen synchronously during the effect function are tracked. - An unexpected extra dependency. Any signal read during the run counts, including reads inside functions the effect calls. A logging helper that reads a
userNamesignal makes the effect re-run whenever the user changes. The chapter onuntracked()shows how to read a signal without tracking it. - Async functions.
effect(async () => { await x; this.y(); })tracks reads before the firstawaitonly. Read every signal you need at the top of the function, then start the async work. - Tests that see stale values. Effects are scheduled, not synchronous. In a
TestBedtest, callTestBed.tick()(orfixture.detectChanges()for component effects) before you assert. - Effects in services. An effect in a
providedIn: 'root'service is a root effect and lives as long as the application does. That suits persistence or logging. It does not suit work that belongs to one screen.
Exercise
A component's constructor creates effect(() => console.log(this.query())). A method then calls this.query.set('a'), this.query.set('ab'), and this.query.set('abc') in the same synchronous block. How many times does the effect log after those writes, and what does it log?
Show answer
Once, logging 'abc'. Effects are scheduled and run during the next change detection pass, so synchronous writes collapse into one run that sees only the latest value.
Exercise
You add effect(() => { ... }) inside ngOnInit and get error NG0203. Give two ways to fix it.
Show answer
Move the effect into the constructor or a field initializer, both of which are injection contexts. Or inject Injector in a field and pass it as effect(fn, { injector: this.injector }).
Exercise
An effect subscribes to a WebSocket channel named by a channel() signal. What goes wrong when the channel changes, and how do you fix it?
Show answer
Each re-run opens a new subscription while the old ones stay open, which leaks connections and duplicates messages. Register the unsubscribe with the onCleanup callback, effect(onCleanup => { const sub = socket.subscribe(this.channel()); onCleanup(() => sub.unsubscribe()); }), so Angular closes the previous subscription before each re-run and when the effect is destroyed.
Exercise
A colleague writes effect(() => this.total.set(this.price() * this.qty())). Why is this a poor choice, and what should replace it?
Show answer
It copies derived state through an effect. total is stale until the effect runs, the effect costs an extra change detection pass, and any code can overwrite total. Replace it with total = computed(() => this.price() * this.qty()).