How to Fix useEffect Cleanup Function
DodaTech
Updated 2026-06-26
1 min read
The Problem
In this quick-fix, you'll learn how to implement cleanup functions to avoid memory leaks. This matters because improper cleanup causes memory leaks stale subscriptions. In real-world applications, this pattern appears in WebSocket connections scroll listeners animation frames.
The Wrong Way
function ChatRoom({ roomId }) {
const [msgs, setMsgs] = useState([]);
useEffect(() => {
const ws = new WebSocket('wss://chat.example.com');
ws.onmessage = (e) => setMsgs(p=>[...p, JSON.parse(e.data)]);
}, [roomId]);
return <div>{msgs.length} messages</div>;
}
Every roomId change creates new WebSocket old stays open -- leak
The Right Way
function ChatRoom({ roomId }) {
const [msgs, setMsgs] = useState([]);
useEffect(() => {
const ws = new WebSocket('wss://chat.example.com');
ws.onmessage = (e) => setMsgs(p=>[...p, JSON.parse(e.data)]);
return () => ws.close();
}, [roomId]);
return <div>{msgs.length} messages</div>;
}
Old WebSocket closes new opens -- no leaks
Prevention
- Return cleanup from useEffect for subscriptions
- Use clearInterval clearTimeout removeEventListener
- Use AbortController for fetch requests
- Test cleanup with StrictMode
FAQ
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