Angular · Senior · Question 11 of 75

How do you clean up inside an effect before it re-runs or is destroyed?

effect((onCleanup) => {
  const id = setInterval(() => this.poll(this.url()), 5000);
  onCleanup(() => clearInterval(id));
});

Explanation

The cleanup runs before the next execution (when url changes) and when the effect is destroyed with its injection context, preventing duplicated intervals.

Further reading

Problem with a question

Angular · Senior · question 11

Test yourself

Take the Angular · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz