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:
- The effect runs and creates a
setInterval. - When
idchanges, Angular calls the cleanup function (clearInterval) so two timers do not run at once. - 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 readyPremium
A concise answer to help you respond confidently on this topic during an interview.