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
This guide is brought to you by DodaTech -- built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
← Previous
How to Fix useEffect Mount Logic Dependencies
Next →
How to Fix useEffect with Ref Dependencies
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro