Skip to main content

What does the cleanup function inside effect() do?

The cleanup function inside effect() is a way to remove or stop something before the effect's next run.

Angular calls it automatically before the effect fires again or when the effect is destroyed.

Example:

ts
import { signal, effect } from '@angular/core'; const id = signal(1); effect(onCleanup => { const timer = setInterval(() => { console.log('ID:', id()); }, 1000); onCleanup(() => clearInterval(timer)); // cleanup before the next run });

What happens:

  1. The effect runs and creates a setInterval.
  2. When id changes, Angular calls the cleanup function (clearInterval) so two timers do not run at once.
  3. Then it runs the effect again.

Summary: cleanup is needed so that old subscriptions, timers, and other side effects do not pile up across repeated runs of the effect.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.