Effect Cleanup and Lifecycle
Clean up resources inside effects.
Why cleanup matters
An effect can start resources: timers, subscriptions, event listeners. Each time the effect re-runs, the old resource must be torn down first — otherwise you leak timers and listeners. Angular provides an onCleanup hook for this.
The onCleanup callback
The effect function receives an onCleanup function. Register a teardown callback with it; Angular calls it before the next run and on destroy.
import { effect } from '@angular/core';
effect((onCleanup) => {
const id = setInterval(() => console.log('tick'), 1000);
onCleanup(() => clearInterval(id));
});All lessons in this course
- Computed Signals
- Effects and Side Effects
- Effect Cleanup and Lifecycle
- linkedSignal and Advanced Patterns