Cleanup for Subscriptions
You'll learn how to properly unsubscribe from external data sources to prevent memory leaks and unexpected behavior.
The Problem with Persistent Connections
Subscriptions are ongoing connections to external data sources like WebSocket connections, observables (RxJS), real-time databases (Firebase), or any API that continuously pushes updates to your component. Unlike a simple fetch request that completes and ends, subscriptions keep running in the background—even after your component unmounts.
If you don't clean them up, you create memory leaks: your app keeps receiving data and trying to update components that no longer exist. This wastes memory, can crash your app, and triggers the dreaded "Can't perform a React state update on an unmounted component" warning.
The Pattern
Always return a cleanup function that unsubscribes when using subscriptions in useEffect:
useEffect(() => {
// Subscribe to the data source
const subscription = dataSource.subscribe(data => {
setData(data);
});
// Cleanup: unsubscribe when effect re-runs or component unmounts
return () => {
subscription.unsubscribe();
};
}, []);
Real-World Example: WebSocket
useEffect(() => {
const socket = new WebSocket('wss://api.example.com/live');
socket.onmessage = (event) => {
setMessages(prev => [...prev, event.data]);
};
// Cleanup: close the connection
return () => {
socket.close();
};
}, []);
The Analogy
Think of a subscription like subscribing to a magazine. If you move houses (component unmounts) but forget to cancel, magazines keep getting delivered to your old address, wasting resources. Cleanup is like notifying the publisher: "Stop sending me magazines."
Key Takeaway: Always unsubscribe from external data sources in your cleanup function to prevent memory leaks and state updates on unmounted components.