Skip to content

How to Fix Observable Subscription Leaks

DodaTech Updated 2026-06-26 1 min read

The Problem

In this quick-fix, you'll learn how to properly unsubscribe from observables in useEffect. This matters because unsubscribed observables cause memory leaks and duplicate handlers. In real-world applications, this pattern appears in real-time data streams Redux store subscriptions RxJS state.

The Wrong Way

function StockTicker({ symbol }) {
  const [price, setPrice] = useState(0);
  useEffect(() => {
    stockPriceStream(symbol).subscribe({ next: (p) => setPrice(p), error: (e) => console.error(e) });
  }, [symbol]);
  return <div>{price}</div>;
}
Every symbol change creates new subscription old stays active -- leak

The Right Way

function StockTicker({ symbol }) {
  const [price, setPrice] = useState(0);
  useEffect(() => {
    const sub = stockPriceStream(symbol).subscribe({ next: (p) => setPrice(p), error: (e) => console.error(e) });
    return () => sub.unsubscribe();
  }, [symbol]);
  return <div>{price}</div>;
}
Old subscription unsubscribed new created -- no leaks

Prevention

  • Always call .unsubscribe() in cleanup
  • Use takeUntil take(1) operators to auto-complete
  • For multi subscriptions use Subject to manage cleanup

FAQ

### Can I use takeUntil for cleanup??

Yes. Create Subject pipe takeUntil(componentDestroyed$). Call .next() and .complete() in cleanup. Cleaner for multiple subscriptions.

Does StrictMode help detect subscription leaks??

Yes double-invokes effects creating and destroying subscriptions. Watch for subscription count growing in DevTools.

What about async pipe in React??

React has no async pipe. Use useEffect directly or libraries like observable-hooks that handle cleanup automatically.

This guide is brought to you by DodaTech -- built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro