Course contentsShow
← React
Lesson 1273 of 2,39632. Lists and Keys Deep DiveFree lesson

Memory Leaks from Incomplete Cleanup

When rapid key changes prevent proper cleanup, leaving listeners, timers, or subscriptions active.

Memory Leaks from Incomplete Cleanup

What you'll learn: How rapid key changes can prevent React from properly cleaning up effects, leaving active listeners, timers, or subscriptions running in memory.

The Cleanup Problem with Keys

When a component's key changes, React unmounts the old instance and mounts a new one. This should trigger cleanup functions from useEffect hooks. However, if keys change rapidly or unpredictably, you can end up in situations where cleanup functions don't get a chance to run before multiple new instances pile up.

The Leak Scenario

Imagine a list where each item subscribes to a WebSocket, starts an interval timer, or adds a scroll listener. If you're generating new keys on every render (common mistake: using Math.random() or Date.now() as keys), React sees every render as a completely new component:

// ❌ BAD: New key every render
items.map((item, index) => (
  <ListItem key={Math.random()} data={item} />
))

Each ListItem mounts fresh, runs its effect, but the previous instance's cleanup may not execute immediately. With rapid re-renders, you accumulate dozens of active subscriptions or timers—all consuming memory and CPU.

Why It Happens

React's cleanup is asynchronous and happens during the commit phase. If you're churning through keys faster than React can commit, those cleanup functions queue up or get lost, leaving resources dangling.

The Fix

Use stable keys that represent the actual identity of your data. When keys remain consistent, React reuses component instances instead of destroying and recreating them:

// ✅ GOOD: Stable key
items.map(item => (
  <ListItem key={item.id} data={item} />
))

Key Takeaway: Unstable keys prevent proper effect cleanup, causing memory leaks from accumulated listeners, timers, and subscriptions—always use stable identifiers as keys.