Sub topic 4
Running Side Effects with effect()
This chapter assumes you already know how writable signals and computed() work. It also assumes you can build a component with a constructor and use Angular dependency injection.
What an effect is
An effect is a function that runs whenever the signals it reads change. A computed() returns a value. An effect returns nothing useful, because its job is to touch something outside the signal graph. Typical targets are localStorage, logging, analytics, a canvas, or a third-party widget.
Angular tracks an effect's dependencies the same way it tracks a computed signal's. Every signal read during the most recent run counts as a dependency. Every effect runs at least once. After that, it runs again only when one of those dependencies 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'));
}
}Effects run asynchronously, as part of change detection. If toggle() is called three times in one event handler, the effect runs once with the final value. It does not run three times.
The injection context requirement
effect() needs an injection context so it can find the DestroyRef that ends it. Valid places to call it are the constructor, a field initializer, or a factory passed to inject(). If you call it inside a method like ngOnInit or a click handler, Angular throws error NG0203.
When you need to create an effect later, pass an injector explicitly:
import { Component, Injector, effect, inject, signal } from '@angular/core';
@Component({
selector: 'app-logger',
template: `<button (click)="startLogging()">Start</button>`,
})
export class LoggerComponent {
private injector = inject(Injector);
count = signal(0);
startLogging() {
const ref = effect(() => console.log('count', this.count()), {
injector: this.injector,
});
// Call ref.destroy() to stop it before the component is destroyed.
}
}An effect created in a component is destroyed together with that component. An effect created in a root service lives as long as the application.
Cleaning up between runs
The effect function receives an onCleanup callback. Angular calls the function you register there before the next run and again when the effect is destroyed. You need it for timers, subscriptions, and listeners.
import { Component, effect, signal } from '@angular/core';
@Component({
selector: 'app-ticker',
template: `<p>Ticks: {{ ticks() }}</p>
<button (click)="intervalMs.set(250)">Faster</button>`,
})
export class TickerComponent {
intervalMs = signal(1000);
ticks = signal(0);
constructor() {
effect(onCleanup => {
const id = setInterval(() => this.ticks.update(t => t + 1), this.intervalMs());
onCleanup(() => clearInterval(id));
});
}
}When intervalMs changes, the old interval is cleared before the new one starts. The ticks update happens inside the interval callback, not during the effect run, so ticks is not tracked as a dependency.
Common errors
| Mistake | Result | Fix |
|---|---|---|
| Using an effect to copy one signal into another | Extra change detection cycles and state that can go stale | Use `computed()` or `linkedSignal()` |
| Reading a signal only inside an `if` branch | The effect stops reacting once the branch is skipped | Read the dependencies you need unconditionally |
| Calling `effect()` in `ngOnInit` | NG0203 error | Move it to the constructor or pass `{ injector }` |
| Forgetting `onCleanup` for timers | Timers or listeners pile up | Register cleanup inside the effect |
Exercise
An effect reads userId() and starts a WebSocket subscription for that user. What happens when userId changes if you don't use onCleanup, and how do you fix it?
Show answer
The effect runs again and opens a second subscription while the first stays open, so messages for both users arrive and resources leak. Register onCleanup(() => subscription.unsubscribe()) inside the effect so the old subscription closes before the next run and when the component is destroyed.
Exercise
Why does calling effect() inside a button click handler fail, and what are two ways to fix it?
Show answer
A click handler is not an injection context, so effect() cannot find a DestroyRef and throws NG0203. You can create the effect in the constructor or a field initializer, or you can inject the Injector and pass it with effect(fn, { injector }).