πŸ”§ Error Fixes
Β· 1 min read

React: Can't Perform a State Update on an Unmounted Component


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

This warning means you’re trying to update state after the component has been removed from the DOM β€” usually from an async operation that completes after navigation.

Why this happens

When a user navigates away or a component unmounts, pending async operations (fetch calls, timers, subscriptions) keep running. When they resolve and call setState, the component no longer exists. This causes a memory leak and the warning.

Fix 1: Cleanup in useEffect

useEffect(() => {
  let cancelled = false;
  
  fetch('/api/data')
    .then(res => res.json())
    .then(data => {
      if (!cancelled) setData(data);
    });

  return () => { cancelled = true; };
}, []);

Fix 2: Use AbortController

useEffect(() => {
  const controller = new AbortController();
  
  fetch('/api/data', { signal: controller.signal })
    .then(res => res.json())
    .then(data => setData(data))
    .catch(err => {
      if (err.name !== 'AbortError') throw err;
    });

  return () => controller.abort();
}, []);

Alternative solution: Use a data-fetching library

Libraries like React Query handle cleanup automatically:

import { useQuery } from '@tanstack/react-query';

const { data } = useQuery({
  queryKey: ['data'],
  queryFn: () => fetch('/api/data').then(r => r.json()),
});

Prevention

  • Always return a cleanup function from useEffect when it contains async operations.
  • Use a data-fetching library (React Query, SWR) instead of raw useEffect + fetch.

Related: React complete guide Β· React Interview Questions Β· React Maximum Update Depth Fix Β· React Hooks Rules Error Fix

πŸ“˜