You’re probably familiar with ngOnDestroy for Angular components/pipes/directives, which cleans things up when an Angular object is destroyed. A typical use case is to unsubscribe from RxJs subscriptions (though there are better-suited tools for this now) or cancel a timer.
Angular Signals introduced the effect() function to run side-effects, including RxJs Observables or timers. As a result, we might want to cancel a timer or an RxJS-based task when the effect runs again in the future, and luckily for us, Angular supports a cleanup function for our effects.
To enable the cleanup function, we pass it as a parameter to the callback registered in our effect:
Then we call it and pass our cleanup code as a param to it using an arrow function:
Here is the full example in action on Stackblitz. This example destroys a component and clears its timer thanks to the effect cleanup function: