Sub topic 5
Running side effects with effect()
This chapter covers effect(): what it is for, when it runs, and which reads it tracks. It assumes you know basic TypeScript, Angular components and dependency injection, and the writable and computed signals from the earlier chapters. Cleanup, destroying effects, and untracked() each get their own later chapter. They appear here only briefly.
What an effect is
A computed signal turns signals into a new value. An effect turns signals into an action. It is a function that Angular runs once and then re-runs whenever a signal it read has changed. It returns nothing that other code can read.
Use an effect when a signal change must reach something outside the signal graph. Typical targets are:
console.logor an analytics calllocalStorageorsessionStorage- a third-party widget that Angular does not manage, such as a chart library or a map
- a manual DOM change that a template binding cannot express
Here is the smallest useful effect, as a component.
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, so both are its dependencies. It logs once when the component is created. After that it logs again each time a click changes count. Because doubled is derived from count, both dependencies change together, and the effect still runs once per change.
When an effect runs
Three rules describe the timing.
- It runs at least once. Angular runs the function after creation so it can discover which signals it reads.
- It runs asynchronously. Calling
count.set(1)does not run the effect inline. Angular marks the effect as dirty and runs it later, during change detection. - It runs only if a dependency changed. Setting a signal to a value that its equality check treats as equal does not notify anything, so the effect stays idle.
The sequence for a button click looks like this.
Because the run is deferred, several writes made in one synchronous block produce one effect run. The effect sees only the final values.
import { Component, signal, effect } from '@angular/core';
@Component({
selector: 'app-batch-demo',
template: `<button (click)="bump()">Bump</button>`,
})
export class BatchDemoComponent {
count = signal(0);
constructor() {
effect(() => console.log('count is', this.count()));
}
bump() {
this.count.set(1);
this.count.set(2);
this.count.set(3);
// The effect logs "count is 3" once, not three times.
}
}Two consequences follow:
- You cannot rely on an effect observing every intermediate value. If you need every value, use an event handler or an RxJS stream.
- You cannot rely on an effect having run immediately after a write. Code that needs the new result right away should read a
computed()instead.
Where in the frame effects run
An effect created inside a component or directive runs as part of change detection for that component. It runs before the component's template is checked, so an effect that updates component state can have that state reflected in the same pass. An effect created in a service that is provided in the root injector runs earlier, before component effects, as part of the application's change detection tick.
Do not depend on the order in which two unrelated effects run. Treat each effect as independent.
Effects in unit tests
Effects do not run when you call set(). A test must trigger a flush. In recent Angular versions you call TestBed.tick(). Older versions used TestBed.flushEffects(). Check which one your version supports. Calling fixture.detectChanges() also flushes component effects.
import { TestBed } from '@angular/core/testing';
import { Component, signal, effect } from '@angular/core';
@Component({ selector: 'app-probe', template: `` })
class ProbeComponent {
value = signal(1);
seen: number[] = [];
constructor() {
effect(() => this.seen.push(this.value()));
}
}
describe('ProbeComponent', () => {
it('records values after change detection', () => {
const fixture = TestBed.createComponent(ProbeComponent);
fixture.detectChanges();
fixture.componentInstance.value.set(2);
fixture.detectChanges();
expect(fixture.componentInstance.seen).toEqual([1, 2]);
});
});What an effect tracks
An effect tracks every signal it reads synchronously while its function body runs. This works the same way as dynamic tracking in computed(). The dependency list is rebuilt on each run, so a signal read in a branch that did not execute is not a dependency.
Reading includes calling a computed signal, calling a signal, and calling anything that reads signals internally. The last case matters. If your effect calls a service method, and that method reads a signal, the effect now depends on that signal. Nothing in the effect's own code shows it.
Reads after an `await` are not tracked
Tracking is active only during the synchronous part of the function. Once the function awaits, the tracking context is gone.
import { Component, signal, effect } from '@angular/core';
@Component({ selector: 'app-async-demo', template: `` })
export class AsyncDemoComponent {
userId = signal(1);
locale = signal('en');
constructor() {
effect(async () => {
const id = this.userId(); // tracked: read before the first await
const response = await fetch(`/api/users/${id}`);
const user = await response.json();
console.log(user, this.locale()); // NOT tracked: read after an await
});
}
}In this example, changing userId re-runs the effect. Changing locale does not. If an async effect must depend on a signal, read that signal before the first await and store it in a local variable.
The effect also gets no automatic cancellation of the in-flight request when it re-runs. That is what cleanup callbacks are for, covered in a later chapter. If your real goal is "load data when a signal changes", an effect is often the wrong tool. A dedicated resource or an RxJS pipeline with switchMap handles overlapping requests properly.
Writing signals inside an effect
Effects can write to signals in current Angular versions. Angular 19 removed the old restriction. In Angular 18 and earlier, you had to pass { allowSignalWrites: true } as an option, and Angular 19 deprecated that option.
The fact that you can write does not mean you should. A write inside an effect creates a second update step: the first change triggers the effect, which makes another change, which may trigger other computeds and effects. The flow becomes hard to follow. It can also loop forever if an effect writes to a signal that it also reads.
import { signal, effect } from '@angular/core';
const count = signal(0);
// Dangerous: reads and writes the same signal, so it keeps re-triggering itself.
effect(() => {
count.set(count() + 1);
});If a signal's value is a function of other signals, express that with computed(). If it needs to be writable and also follow other signals, the linkedSignal() chapter covers that case.
A realistic example: persisting state
Saving a user preference is a good fit for an effect. The change must reach localStorage, which lives outside Angular, and nothing needs to read a result back.
import { Component, signal, effect } from '@angular/core';
type Theme = 'light' | 'dark';
@Component({
selector: 'app-theme-switch',
template: `
<button (click)="toggle()">Theme: {{ theme() }}</button>
`,
})
export class ThemeSwitchComponent {
theme = signal<Theme>(this.load());
constructor() {
effect(() => {
localStorage.setItem('theme', this.theme());
});
}
toggle() {
this.theme.update((t) => (t === 'light' ? 'dark' : 'light'));
}
private load(): Theme {
return localStorage.getItem('theme') === 'dark' ? 'dark' : 'light';
}
}On creation the effect writes the initial value back to storage. That is harmless here, but it shows rule 1: the first run always happens. If a first run would do something unwanted, such as sending an analytics event for a value nobody changed, guard against it in the effect or choose another mechanism.
Server-side rendering needs one more thought. localStorage does not exist on the server, so code like this needs a guard, for example with isPlatformBrowser, or afterNextRender for browser-only work.
Creating an effect: injection context
effect() registers itself with the current injector so Angular can destroy it when its owner is destroyed. That requires an injection context. The places you can call it without extra work are:
- a constructor
- a field initializer in a class that Angular creates
- a function that runs inside
runInInjectionContext
Calling effect() from an ordinary method, such as a click handler, throws an error saying it must be called from an injection context. The fix is to create the effect in the constructor, or to pass an injector in the options. The next chapter on lifecycle and cleanup describes both options, along with destroy() and manualCleanup.
import { Component, signal, effect } from '@angular/core';
@Component({ selector: 'app-field-effect', template: `` })
export class FieldEffectComponent {
size = signal(10);
// A field initializer is also an injection context.
private logSize = effect(() => console.log('size', this.size()));
}effect() returns an EffectRef. Keep it if you need to stop the effect early with ref.destroy(). Most effects never need that, because Angular destroys them with their owner.
Effects compared with the alternatives
The effect is the last resort among three tools, which the next chapter compares in depth. For now, keep this quick check.
| You want to | Use |
|---|---|
| Compute a value from other signals | `computed()` |
| React to a user action or an event | An event handler |
| Push signal changes to something outside Angular | `effect()` |
Effects are a poor choice for copying one signal into another. They are also a poor choice for triggering an HTTP call that a user action started, because the handler already knows when the action happened.
Common mistakes
- Expecting synchronous runs. Code that reads the result of an effect right after
set()sees stale data. Read acomputed()instead. - Expecting one run per write. Several writes in one tick produce one run, with the final values.
- Reading signals after
await. Those reads are silently ignored for tracking. - Hidden dependencies. A helper that reads a signal makes the effect depend on it. Move the read out, or wrap it in
untracked(), which a later chapter covers. - Creating effects outside an injection context. This throws at run time, not at compile time.
- Using effects for derived state. It works, but adds a render cycle, and it often shows flicker or
ExpressionChanged-style problems thatcomputed()avoids.
Exercise
A component has query = signal('') and page = signal(1). Its constructor contains effect(async () => { await Promise.resolve(); console.log(this.query(), this.page()); }). A user types in a search box, and the handler calls query.set('a') and then page.set(2) in the same function. How many times does the effect run after this, and which of the two signals actually triggers re-runs?
Show answer
The effect runs once on creation. Both writes happen in the same synchronous block, but the effect re-runs only if a tracked signal changed. Both reads come after the await, so neither signal is tracked. The effect has no dependencies and never re-runs, so the two writes cause no further runs. To make the effect depend on them, read this.query() and this.page() into local variables before the await. Then the two writes would be batched and the effect would run once more with 'a' and 2.
Exercise
Why does this fail, and how would you fix it? onSave() { effect(() => localStorage.setItem('draft', this.draft())); }
Show answer
effect() needs an injection context so Angular can tie the effect to an owner and destroy it later. A click-handler method is not an injection context, so the call throws. Move the effect() call into the constructor, or pass an injector option. Better still, because a click already marks the moment of saving, the handler could call localStorage.setItem directly and skip the effect.