useEffect Cleanup and Re-run Issues
You'll learn how unstable keys cause effects to clean up and re-initialize unnecessarily, leading to redundant data fetches and broken subscriptions.
The Hidden Side Effect of Key Changes
When a component's key changes, React doesn't just unmount and remount the DOM—it runs through the entire component lifecycle again. This means any useEffect hooks fire their cleanup functions, then reinitialize completely.
If your effect subscribes to a WebSocket, fetches data, or sets up event listeners, unstable keys will tear down and rebuild these connections every single render—even when the data itself hasn't changed.
The Problem in Practice
Imagine a user list where each row fetches detailed profile data:
// ❌ Using index as key
users.map((user, index) => (
<UserRow key={index} userId={user.id} />
))
Inside UserRow:
useEffect(() => {
const controller = new AbortController();
fetch(`/api/users/${userId}`, { signal: controller.signal })
.then(res => res.json())
.then(setProfile);
return () => controller.abort(); // Cleanup
}, [userId]);
When the list re-sorts, every index changes. React treats each UserRow as a "new" component, running cleanup (aborting the fetch) then immediately starting a new fetch for the same user. You've just doubled your API calls unnecessarily.
The same applies to WebSocket connections closing and reopening, timers resetting, and animation state getting lost.
The Stable Key Solution
// ✅ Stable key preserves effect state
users.map(user => (
<UserRow key={user.id} userId={user.id} />
))
Now effects only clean up when the component actually unmounts, not on every re-sort.
Key Takeaway: Unstable keys force React to run effect cleanup and re-initialization on every render, causing redundant subscriptions, data fetches, and broken external connections—use stable IDs to preserve effect lifecycle.