Sub topic 7
Injection context, cleanup and destroying effects
This chapter assumes you know basic TypeScript, Angular components and dependency injection, and the signal basics from earlier chapters: signal(), computed() and the first effect() example. Here you will learn where an effect may be created, how to clean up after one, and how to stop one.
Where effects can be created
effect() needs access to Angular's dependency injection system. It uses that access to find the surrounding component, directive or service, so it can destroy the effect when that owner is destroyed. Code that runs inside a place where inject() works is in an injection context.
These places are injection contexts:
- A field initializer of a class that Angular creates.
- The constructor of a component, directive or service.
- A function that runs inside
runInInjectionContext().
If you call effect() somewhere else, such as in a click handler or in ngOnInit(), Angular throws an error saying effect() can only be used within an injection context.
import { Component, signal, effect } from '@angular/core';
@Component({
selector: 'app-logger',
template: `<button (click)="count.update((c) => c + 1)">{{ count() }}</button>`,
})
export class LoggerComponent {
count = signal(0);
// Field initializer: an injection context.
private readonly logger = effect(() => {
console.log('count is', this.count());
});
}If you must create an effect later, for example after a user action, inject an Injector first and pass it in the options.
import { Component, Injector, inject, signal, effect } from '@angular/core';
@Component({
selector: 'app-late-effect',
template: `<button (click)="start()">Start logging</button>`,
})
export class LateEffectComponent {
private readonly injector = inject(Injector);
value = signal(0);
start() {
effect(() => console.log('value is', this.value()), {
injector: this.injector,
});
}
}Clicking the button twice creates two effects. Guard against this if you only want one.
When an effect runs and is destroyed
An effect created in a component is tied to that component's lifetime. When the component is destroyed, Angular destroys the effect, and it never runs again. The same holds for effects in services and directives.
The diagram below shows the life of an effect.
Effects do not run at the moment a signal changes. They are scheduled, and Angular runs them later during change detection. Several changes to one signal before that point cause a single run.
Cleaning up with onCleanup
Many side effects leave something behind: a timer, a subscription, an event listener. If the effect runs again, the earlier one must be removed first. The callback receives an onCleanup function for this. The function you register runs before the next run of the effect and also when the effect is destroyed.
import { Component, input, effect } from '@angular/core';
@Component({
selector: 'app-delayed-log',
template: ``,
})
export class DelayedLogComponent {
id = input.required<number>();
constructor() {
effect((onCleanup) => {
const id = this.id();
const timer = setTimeout(() => console.log('loaded', id), 500);
onCleanup(() => clearTimeout(timer));
});
}
}If id changes from 1 to 2 within 500 ms, the cleanup clears the timer for 1. Only the timer for 2 fires. Without the cleanup, you would see a stale loaded 1 message.
Call onCleanup during the run, after you create the resource. Register one cleanup per resource.
Destroying an effect by hand
effect() returns an EffectRef. Its destroy() method stops the effect before its owner is destroyed.
import { signal, effect, Injector, inject, Component } from '@angular/core';
@Component({
selector: 'app-manual',
template: `<button (click)="stop()">Stop</button>`,
})
export class ManualComponent {
count = signal(0);
private readonly ref = effect(() => {
console.log('count', this.count());
});
stop() {
this.ref.destroy();
}
}After destroy(), changes to count no longer log anything. Any registered cleanup runs once at that point.
By default, Angular destroys effects for you. Manual destruction is mostly useful for effects that you create with a custom Injector, since that injector may outlive the work the effect was meant for.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Calling `effect()` in `ngOnInit()` or an event handler | Error about injection context | Move it to a field or constructor, or pass `injector` |
| Forgetting `onCleanup` for timers or listeners | Stale callbacks fire after the inputs change | Register cleanup after creating the resource |
| Creating an effect in a method that runs many times | Several effects pile up | Keep the `EffectRef` and destroy it, or create it once |
| Expecting an effect to run right after `set()` | Logs appear later than expected | Effects run during change detection, not synchronously |
Exercise
An effect watches a userId signal and opens a WebSocket for that user inside its callback. What problem appears when userId changes, and how do you fix it?
Show answer
The effect runs again and opens a new socket, but the old socket stays open, so connections pile up and old messages keep arriving. Fix it by calling onCleanup(() => socket.close()) right after creating the socket. Angular then closes the old socket before each re-run and when the effect is destroyed.
Exercise
You need to start an effect when a user clicks a button. Calling effect() in the click handler throws an error. Give two ways to solve this.
Show answer
First, create the effect in the constructor or a field initializer and make it depend on a signal that the click handler sets, such as started. Second, inject Injector in the constructor and call effect(..., { injector: this.injector }) in the handler, or wrap the call in runInInjectionContext(this.injector, () => effect(...)).