DEV Community

Dominik Paszek
Dominik Paszek

Posted on

The Angular memory leak that kept sneaking into my code (and how to fix it)

Hey DEV community,

In my day-to-day work reviewing Angular codebases, there is one specific memory leak that constantly sneaks into pull requests. It’s a silent performance killer that happens when we navigate between pages, and it usually slips right past standard testing.

Instead of just writing another comment on a PR, I realized it's much easier to show the problem visually. So, I decided to step completely out of my comfort zone and record my first-ever YouTube coding tutorial.

I quickly learned that centering a div is an absolute breeze compared to editing out my "umms" and trying to animate RxJS streams.

Here is the "TL;DR" of what I cover, in case you prefer reading over watching:
The "Unsubscribe from Everything" Myth

A lot of developers are taught to aggressively unsubscribe from absolutely every observable. But Angular's HttpClient returns "Cold Observables". They emit a value, complete, and clean up after themselves automatically. No memory leak there.

The real danger comes from "Hot Observables" like a global BehaviorSubject (e.g., in a shared service or NgRx store). If your component subscribes to it, and the user navigates away, the component is visually destroyed. But the RxJS stream doesn't know that. It keeps firing data at the ghost component in the background, and your RAM usage slowly climbs.

The Modern Angular 16+ Fix

We used to do the whole ngOnDestroy dance with .unsubscribe(). Now, we have a much cleaner way: takeUntilDestroyed().

export class UserProfileComponent implements OnInit {
  private destroyRef = inject(DestroyRef);
  private userService = inject(UserService);

ngOnInit() {
    this.userService.getUserData()
     .pipe(takeUntilDestroyed(this.destroyRef)) // This single line fixes the leak
     .subscribe(data => {
        console.log('Data received:', data);
      });
  }
}
Enter fullscreen mode Exit fullscreen mode

Nested Subscribes (Callback Hell)

The other thing I tackle in the video is when one API call depends on another (like fetching a user ID, then fetching their posts). Nesting subscribe inside another subscribe creates race conditions. I show how to flatten this using the switchMap operator, which also automatically cancels outdated in-flight requests in the Network tab.
The Video

I tried to make this as visual as possible. I actually open up the Chrome DevTools Memory tab to show the exact moment the RAM spikes, how to track detached DOM nodes, and how the memory Delta drops back to zero after the fix.

Since this is literally my first time recording, editing, and trying to make technical animations, I’d really appreciate your honest feedback. Did the DevTools explanation make sense? And please, any tips from experienced video creators on how to make the next one less painful to edit would be amazing!

Thanks for reading (and watching)!

Top comments (0)