0Pricing
Angular Academy · Lesson

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

  1. Computed Signals
  2. Effects and Side Effects
  3. Effect Cleanup and Lifecycle
  4. linkedSignal and Advanced Patterns
← Back to Angular Academy