As you probably know when you subscribe to an observable or event in JavaScript, you usually need to unsubscribe at a certain point to release memory in the system. Otherwise, you will have a memory leak.

Let’s see the most common cases that you will need to unsubscribe inside the ngOnDestroy lifecycle hook.

Forms —

This also applies to any form control.

The Router —

According to the official documentation, Angular should unsubscribe for you, but apparently, there is a bug.

Renderer Service —

Infinite Observables —

When you have an infinite sequence, you should unsubscribe (unless you have a special case), for example when using the interval() or the fromEvent() observables.

Redux Store —

ngrx/store and redux-angular select method returns an observable. Therefore they have to be cleaned.

Don’t Unsubscribe

Async pipe —

When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.

@HostListener —

Finite Observable —

When you have a finite sequence, usually you don’t need to unsubscribe, for example when using the HTTP service or the timer observable.

Final tip —

You should be more declarative and try as little as possible to call the unsubscribe method. You can read more about the subject in this article — RxJS: Don’t Unsubscribe.

For example:

Follow me on Medium or Twitter to read more about Angular, Vue and JS!