Course contentsShow
← React
Lesson 575 of 2,39616. useEffect for Data FetchingFree lesson

Setting State After Unmount Warning

Understand the 'Can't perform a React state update on an unmounted component' warning and why it appears.

Setting State After Unmount Warning

What you'll learn: Why React warns you about setting state on unmounted components and what causes this common issue.

When fetching data with useEffect, you'll often encounter this warning:

Warning: Can't perform a React state update on an unmounted component.

What Causes This Warning?

This happens when your component starts an asynchronous operation (like a fetch), but the component unmounts before that operation completes. When the fetch finally finishes, it tries to call setState, but the component no longer exists in the DOM.

Here's the typical scenario:

function UserProfile({ userId }) {
  const [user, setUser] = useState(null);

  useEffect(() => {
    fetch(`/api/users/${userId}`)
      .then(res => res.json())
      .then(data => setUser(data)); // ⚠️ Component might be gone!
  }, [userId]);

  return <div>{user?.name}</div>;
}

If the user navigates away before the fetch completes, React triggers the warning because setUser(data) executes after unmount.

Why Does React Warn You?

Think of it like mailing a letter to a demolished building. The post office (React) warns you because:

  1. It's wasteful — you're trying to update something that doesn't exist
  2. It might indicate a memory leak — the fetch callback still holds references to the unmounted component
  3. It suggests missing cleanup — you should cancel in-flight operations

The warning itself is harmless (no crash), but it indicates your code should handle cleanup properly.

Key Takeaway: The "setting state after unmount" warning appears when asynchronous operations complete after a component has unmounted, signaling that you need cleanup logic to cancel or ignore those operations.