angularoptimizationmemory-leaksondestroylifecycle-hook

How to use OnDestroy properly


I've seen a lot of question related to ngOnDestroy. I think many of us not using it correctly or not using it at all.
I just want to see a list of tips how can you properly use ngOnDestroy and what should we do in the best scenario to prevent memory leaks, speed up and optimize web apps.
What do you must to do in every case when you use it?(What are the steps you MUST to take?)
How far you need to go if you want to do it perfectly? Nullifying all references etc.


Solution

  • One scenario where you are using Observable and subscribing it in a component and are getting a stream of data i.e Firebase. You should use ngOnDestroy and unsubscribe it when you leave the page to prevent the memory leak.

    ngOnDestroy() {
      this.data.unsubscribe();
    }