Skip to content

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

### When does cleanup function run??

On unmount and before effect re-runs when deps change. Ensures old subscriptions torn down before new ones created.

Can I have multiple cleanup functions??

Yes each useEffect can have its own cleanup. Multiple effects are fine each manages own lifecycle.

What if cleanup throws??

React catches errors but subsequent effects may not run. Wrap cleanup in try-catch.

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