Sub topic 7
Injection context, cleanup and destroying effects
This chapter covers the lifecycle of an effect(). It explains where you may create one, how Angular destroys it, how to register cleanup work, and how to stop an effect yourself. It assumes you know basic TypeScript, Angular components and dependency injection, and how signal() and computed() work. It also assumes you know when an effect runs. Earlier chapters covered all of these.
Why effects need an injection context
An effect is not a plain function call. Angular ties each effect to an owner so it can destroy the effect when that owner goes away. For a component, the owner is the component itself. When the component is destroyed, its effects are destroyed too.
Angular finds the owner through dependency injection. effect() asks for a DestroyRef (the object Angular uses to register "run this when I am destroyed" callbacks). It can only get one inside an injection context. An injection context is a stretch of code where inject() is allowed to work.
These places are injection contexts:
- A class field initializer in a component, directive, service or pipe.
- The constructor of those classes.
- A factory function passed to a provider, such as
useFactory. - Code run inside
runInInjectionContext().
Most effects are created in the constructor, which is the pattern used in the earlier examples:
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);
}
}You can also assign an effect to a class field. This is handy when you want a name for it, which you will need later to read its EffectRef:
import { Component, signal, effect } from '@angular/core';
@Component({
selector: 'app-logger',
template: `<button (click)="level.set(level() + 1)">{{ level() }}</button>`,
})
export class LoggerComponent {
level = signal(0);
private readonly logEffect = effect(() => {
console.log('level is', this.level());
});
}The common error: creating an effect too late
If you call effect() from a method that runs later, such as an event handler or a lifecycle hook, there is no injection context. Angular throws an error saying that effect() can only be used within an injection context.
import { Component, signal, effect } from '@angular/core';
@Component({
selector: 'app-broken',
template: `<button (click)="start()">Start</button>`,
})
export class BrokenComponent {
count = signal(0);
start() {
// Throws: no injection context here.
effect(() => console.log(this.count()));
}
}You have two ways to fix this. The first is to move the effect() call into the constructor or a field, and let it react to a signal that start() changes. The second is to pass an Injector explicitly.
import { Component, Injector, inject, signal, effect } from '@angular/core';
@Component({
selector: 'app-fixed',
template: `<button (click)="start()">Start</button>`,
})
export class FixedComponent {
private readonly injector = inject(Injector);
count = signal(0);
start() {
effect(() => console.log(this.count()), { injector: this.injector });
}
}The injector option tells effect() where to look for its DestroyRef. The effect is still destroyed with the component. Be careful, though: each click on the button creates another effect. They pile up until the component is destroyed. Creating effects on demand is rarely what you want. Prefer one effect in the constructor that reacts to state.
If you have a function that creates effects and may be called from outside an injection context, you can wrap the call:
import { Injector, runInInjectionContext, signal, effect } from '@angular/core';
export function startLogging(injector: Injector) {
const level = signal(0);
runInInjectionContext(injector, () => {
effect(() => console.log('level', level()));
});
return level;
}runInInjectionContext() makes inject() work inside the callback, so effect() can find its owner.
When an effect is destroyed
The owner decides how long an effect lives.
| Where the effect is created | When it is destroyed |
|---|---|
| Component or directive | When that component or directive is destroyed |
| Root service (`providedIn: 'root'`) | When the application is destroyed |
| Created with an explicit `injector` option | When the owner of that injector is destroyed |
| Created with `manualCleanup: true` | Only when you call `destroy()` |
After destruction, the effect never runs again, even if its signals change. You do not need to unsubscribe or clean anything up for the effect itself. This is a difference from RxJS subscriptions, which you must close manually unless a helper does it for you.
A scheduled run is not guaranteed to happen. If the owner is destroyed before Angular runs a pending effect, the effect is skipped.
Cleanup with onCleanup
An effect often starts something that must be stopped: a timer, an event listener, an in-flight request. Without cleanup, an old timer would still fire after the effect has run again with new values.
Angular passes your effect function a single argument, onCleanup. You give it a callback. Angular calls that callback in two situations:
- Right before the effect runs again.
- 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));
});
}
}Suppose id changes from 1 to 2 after 200 ms. Before the effect runs for 2, Angular calls the cleanup from the first run, so the timer for 1 is cleared. Only the log for 2 appears.
The sequence of events looks like this:
Rules for onCleanup
- Call
onCleanupduring the run, ideally right after you create the resource it cleans up. A cleanup registered for a resource that you create later can be missed if the function throws between the two. - Each run registers its own cleanup. The callback from the previous run is not carried over, so register it again on every run.
- Keep the callback synchronous and fast. It runs in the middle of Angular's scheduling.
- The cleanup closes over the variables of the run that registered it. That is why the example reads
idinto aconstfirst: the cleanup and the timer both refer to the same run.
Here is a second, common case: a DOM event listener tied to a signal.
import { Component, signal, effect } from '@angular/core';
@Component({
selector: 'app-key-logger',
template: `<p>Listening: {{ active() }}</p>`,
})
export class KeyLoggerComponent {
active = signal(true);
constructor() {
effect((onCleanup) => {
if (!this.active()) {
return;
}
const handler = (e: KeyboardEvent) => console.log('key', e.key);
window.addEventListener('keydown', handler);
onCleanup(() => window.removeEventListener('keydown', handler));
});
}
}When active becomes false, Angular first runs the cleanup, which removes the listener. The effect then runs, sees false and returns without adding a new one. Because the if runs before active() is skipped, the effect still tracks active on every run. That is what lets it wake up again when active returns to true.
Destroying an effect yourself
effect() returns an EffectRef. It has one method, destroy(). Calling it stops the effect immediately and runs the pending cleanup.
import { Component, signal, effect, EffectRef } from '@angular/core';
@Component({
selector: 'app-stoppable',
template: `
<button (click)="count.set(count() + 1)">Add</button>
<button (click)="stop()">Stop logging</button>
`,
})
export class StoppableComponent {
count = signal(0);
private readonly logRef: EffectRef = effect(() => {
console.log('count', this.count());
});
stop() {
this.logRef.destroy();
}
}After stop(), clicking "Add" still changes count, but nothing is logged. Calling destroy() a second time does nothing harmful.
manualCleanup
By default, an effect is destroyed with its owner. Sometimes you need an effect that outlives it, for example one created in a component but meant to keep running until some other condition is met. Pass manualCleanup: true:
import { signal, effect, Injector } from '@angular/core';
export function watchUntilStopped(injector: Injector) {
const value = signal(0);
const ref = effect(() => console.log('value', value()), {
injector,
manualCleanup: true,
});
return { value, stop: () => ref.destroy() };
}With manualCleanup: true, Angular does not register the effect with a DestroyRef. You are now responsible for calling destroy(). If you forget, the effect stays alive for as long as something keeps its signals reachable, which can be a memory leak.
Checking your understanding of tracking
Cleanup interacts with dependency tracking. The cleanup callback is not part of the tracked reads. Signals you read inside the callback you pass to onCleanup do not become dependencies. Only reads in the main body of the effect function during that run count.
If you need to read a signal in the body without making it a dependency, use untracked(), which a later chapter covers in detail.
Summary of rules
- Create effects in an injection context: constructor, field initializer, or inside
runInInjectionContext(). - Outside such a context, pass
{ injector }. - Effects are destroyed automatically with their owner. Do not unsubscribe by hand.
- Use
onCleanupfor timers, listeners and requests. Register it on every run. - Call
destroy()on theEffectRefto stop an effect early. - Use
manualCleanup: trueonly when you will calldestroy()yourself.
Exercise
A component method load() runs on a button click and calls effect(() => console.log(this.id())). Angular reports that effect() was called outside an injection context. Give two ways to fix this, and say which one you would choose.
Show answer
First, move the effect() call into the constructor or a field initializer, so it reacts to id whenever it changes, and let load() only change signals. Second, inject Injector into the component and call effect(..., { injector: this.injector }) inside load(). The first is better. With the second, every click creates one more effect, and they all stay alive until the component is destroyed.
Exercise
An effect starts setInterval using a signal period(). When period changes, two intervals now run at once. What is missing, and where does it go?
Show answer
The effect does not stop the old interval. Store the id returned by setInterval in a const, then call onCleanup(() => clearInterval(id)) in the same run. Angular calls that cleanup before the next run and when the effect is destroyed, so only one interval is active at a time.
Exercise
What changes if you create an effect with manualCleanup: true, and what must you do?
Show answer
Angular no longer destroys the effect when its owner is destroyed. You must keep the returned EffectRef and call destroy() yourself when the effect is no longer needed. If you do not, the effect keeps running and can leak memory.