Course contentsShow
← React
Lesson 552 of 2,39615. useEffect FundamentalsFree lesson

When Cleanup Runs: Before Re-run

Understanding that cleanup executes before the effect runs again when dependencies change, preventing stale subscriptions.

When Cleanup Runs: Before Re-run

What You'll Learn

You'll understand that cleanup functions execute before the effect runs again when dependencies change, ensuring you don't accumulate stale subscriptions or side effects.

The Timing of Cleanup

When you return a cleanup function from useEffect, React doesn't just run it when the component unmounts. It also runs cleanup before re-executing the effect whenever dependencies change.

This timing is crucial for preventing bugs.

Why This Matters

Imagine you're subscribing to a data source in your effect:

useEffect(() => {
  const subscription = subscribe(userId);
  return () => subscription.unsubscribe();
}, [userId]);

When userId changes from "user-1" to "user-2", here's what happens:

  1. First: React calls your cleanup function, unsubscribing from "user-1"
  2. Then: React runs the effect again, subscribing to "user-2"

Without cleanup running first, you'd have two active subscriptions — one stale (user-1) and one current (user-2). This causes memory leaks and duplicate updates.

The Analogy: Changing Channels

Think of it like a radio. When you change stations:

  • First, you disconnect from the old frequency (cleanup)
  • Then, you tune in to the new frequency (effect re-runs)

If you didn't disconnect first, you'd hear both stations at once — chaos!

The Sequence

Every time dependencies change:

  • Previous cleanup runs (if it exists)
  • New effect runs with current values
  • New cleanup is registered for next time

This ensures only one side effect is active at any moment.

Key Takeaway: Cleanup runs before the effect re-executes on dependency changes, preventing stale side effects from accumulating and ensuring clean transitions between effect states.