Course contentsShow
← JavaScript
Lesson 2112 of 2,72344. Reactive PatternsFree lesson

Unsubscribing and Memory Leaks

Learn why failing to unsubscribe creates memory leaks and how to implement proper cleanup patterns.

Unsubscribing and Memory Leaks

You'll learn why forgetting to unsubscribe from observers creates memory leaks and how to implement proper cleanup.

The Problem

When you register an observer with a subject, the subject stores a reference to that observer. If you never explicitly remove that observer, it remains in memory even after you're done with it. This is a memory leak — the observer can't be garbage collected because the subject still holds a reference to it.

Think of it like subscribing to a magazine. If you move away but never cancel your subscription, the publisher keeps your old address on file indefinitely, wasting space in their database. Similarly, uncancelled observers waste memory.

The Solution: Unsubscribe Methods

Your subject should provide a way to remove observers:

class Subject {
  constructor() {
    this.observers = [];
  }

  subscribe(observer) {
    this.observers.push(observer);
    
    // Return unsubscribe function
    return () => {
      const index = this.observers.indexOf(observer);
      if (index > -1) {
        this.observers.splice(index, 1);
      }
    };
  }

  notify(data) {
    this.observers.forEach(observer => observer.update(data));
  }
}

// Usage with cleanup
const subject = new Subject();
const unsubscribe = subject.subscribe({ update: (d) => console.log(d) });

// Later, when done:
unsubscribe(); // Observer removed, can be garbage collected

Common Pattern

Returning an unsubscribe function from subscribe() is the standard pattern. This gives the caller immediate access to cleanup logic without needing to track the observer reference separately.

Always call unsubscribe when:

  • A component unmounts
  • A feature is disabled
  • You're done listening to changes

Key Takeaway: Always provide and call unsubscribe methods to prevent observers from lingering in memory after they're no longer needed, avoiding memory leaks in long-running applications.