Course contentsShow
← JavaScript
Lesson 1881 of 2,72339. Memory Management and GCFree lesson

Memory Leak Patterns in Frameworks

Common leaks in React, Vue, or Angular from improper component unmounting or listener cleanup.

Memory Leak Patterns in Frameworks

You'll learn how React, Vue, and Angular components can accidentally create memory leaks when cleanup isn't handled properly.

Modern frameworks manage component lifecycles for you, but that doesn't mean you're immune to memory leaks. The most common culprits are event listeners, timers, and subscriptions that outlive the component that created them.

The Problem

When a framework component mounts, it might:

  • Add event listeners (window resize, scroll, custom events)
  • Start intervals or timeouts
  • Subscribe to observables, stores, or third-party services

If these aren't cleaned up when the component unmounts, they keep running and holding references to the now-defunct component. The framework removed your component from the UI, but JavaScript's garbage collector can't reclaim the memory because your forgotten listener still references it.

Framework-Specific Patterns

React: Forgetting cleanup in useEffect hooks or not canceling subscriptions in class component componentWillUnmount.

Vue: Not removing listeners added in mounted when beforeUnmount fires, or forgetting to unsubscribe from watchers.

Angular: Keeping RxJS subscriptions alive after ngOnDestroy, especially when subscribing directly without the async pipe.

Think of it like renting an apartment: the framework is the landlord who shows you out (unmount), but you left your TV subscription running and forwarding mail to the old address. You've moved, but you're still paying—and the old apartment can't be rented to anyone else.

The Solution Pattern

Always pair setup with teardown. Return cleanup functions, call clearInterval, invoke unsubscribe methods, and remove listeners explicitly in your framework's destruction lifecycle hook.

Key Takeaway: Framework components don't automatically clean up everything—you must explicitly remove listeners, timers, and subscriptions during unmount or your component's memory will leak despite being removed from the DOM.