0 day streak
javascript / intermediate
Snippet

Flexible Cleanup with DestroyRef

DestroyRef allows you to register cleanup logic anywhere within an injection context. It is a more flexible alternative to the traditional ngOnDestroy lifecycle hook, especially when using functional patterns.

snippet.js
javascript
1
2
3
4
5
6
7
const destroyRef = inject(DestroyRef);
const subscription = interval(1000).subscribe(console.log);
destroyRef.onDestroy(() => {
subscription.unsubscribe();
console.log('Cleanup complete');
});
angular
Breakdown
1
inject(DestroyRef)
Obtains a reference to the current component's or provider's destruction trigger.
2
onDestroy(() => ...)
Registers a callback function to be executed when the context is destroyed.