Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

React: state update on an unmounted component

This warning comes from a setState after unmount, usually an unresolved request. React 18 removed the warning, but the race still leaks: cancel and guard.

~6 min readReact
#React#Hooks#Async#Debugging
A React component crate gone dark while a cyan request arrow still returns to it, an amber abort switch beside it

Introduction & Quick Summary

The warning text is exact and easy to search, which is why it still gets asked about years after it was removed:

code
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

It means a setState call reached a component that no longer exists. The update is dropped, so nothing breaks visually, but the code that made the call is still running after it stopped being useful. In almost every case the caller is an unresolved promise from fetch, a timer, a subscription, or an event handler that outlived navigation.

React 18 removed this warning. Concurrent rendering and StrictMode make temporary unmount and remount normal, so the warning produced false positives and was deleted. Removing the warning did not remove the race: the request still resolves, the state still updates nothing, and any work after the update still runs. Applications that relied on the warning for cleanup now leak silently.

The durable fixes:

  • Cancel the request with AbortController and ignore AbortError deliberately.
  • Guard with a flag captured in the effect, when the API cannot be cancelled.
  • Use a data library that binds results to the current key, so stale responses are discarded.
  • Clear timers, listeners, and subscriptions in the same effect that created them.

Core Mechanics, Signatures & Reproducible Setup

useEffect runs after commit and its cleanup runs before the next effect execution or unmount. Cleanup is the only place React tells you that the component is going away, so every side effect that can outlive the render must be registered there.

tsx
import { useEffect, useState } from "react"; export function Profile({ id }: { id: string }) { const [name, setName] = useState<string | null>(null); useEffect(() => { let active = true; fetch(`/api/users/${id}`) .then((res) => res.json()) .then((data) => { if (!active) return; // component unmounted or id changed setName(data.name); }); return () => { active = false; }; }, [id]); return <p>{name ?? "loading"}</p>; }

A reproducible setup is a route that mounts this component, navigates away before the response arrives, and a server that delays the response by one second. With React 17 the warning appears; with React 18 or 19 it does not, which is exactly why the guard must be written for correctness rather than to silence a console message.

React versionWarningWhat still happens
16 and 17printed in developmentdropped update, leaked work
18removeddropped update, leaked work
19removeddropped update, leaked work
StrictMode, devnever reliableeffects mount twice on purpose

Key Comparison Table

ApproachCancels networkCode costCorrect when
AbortControlleryesa few lines per effectfetch or any abort-aware API
ignore flagno, discards resultthree linesthird-party promise without abort
Data library keyed by idyes, per keya dependencymany components fetch similar data
Move fetch to the parentnoarchitectural changechildren mount and unmount often
useSyncExternalStorenot applicablea store per sourceexternal subscription, not a request

An abort signal is the stronger fix because it stops the transfer and the memory that would have held the response. The flag is the pragmatic fix for libraries that ignore signals. Neither replaces correct dependency arrays: a missing entry causes the stale-response race even while the component stays mounted.

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. StrictMode runs effects twice in development

React mounts, unmounts, and remounts each component once in development under StrictMode. The cleanup runs in between, so a fetch started in the first mount resolves against a component instance that was already discarded.

tsx
useEffect(() => { const controller = new AbortController(); load(controller.signal).then(setData).catch((error) => { if (error.name === "AbortError") return; // expected during remount setError(error); }); return () => controller.abort(); }, []);

If the request fires twice in development and once in production, that is StrictMode doing its job of exposing a missing cleanup, not a bug in React.

2. AbortController with fetch

Pass the signal, then distinguish cancellation from failure. An aborted fetch rejects with a DOMException named AbortError, and reporting it as a network failure creates false alerts.

tsx
useEffect(() => { const controller = new AbortController(); async function run() { try { const res = await fetch(`/api/orders/${id}`, { signal: controller.signal }); if (!res.ok) throw new Error(`HTTP ${res.status}`); setOrder(await res.json()); } catch (error) { if (controller.signal.aborted) return; setError(error as Error); } } run(); return () => controller.abort(); }, [id]);

Check controller.signal.aborted rather than the error name when several layers wrap the error; a library may rethrow the abort as a plain Error.

3. The ignore flag for APIs that cannot abort

Promise-based clients that do not accept a signal still resolve after unmount. A flag in the effect closure is enough, and it also covers a changed dependency.

tsx
useEffect(() => { let ignore = false; client.query({ id }).then((result) => { if (ignore) return; setRows(result.rows); }); return () => { ignore = true; }; }, [id]);

The flag does not stop the request, so a slow endpoint still costs bandwidth. Prefer abort where available, and treat the flag as a compatibility layer.

4. Timers, intervals, and animation frames

Timers keep firing after unmount and each tick calls setState. Clear them in cleanup, including the interval id created inside a conditional branch.

tsx
useEffect(() => { const id = window.setInterval(() => setTick((t) => t + 1), 1000); return () => window.clearInterval(id); }, []);

The same pattern applies to requestAnimationFrame, setTimeout chains, and IntersectionObserver instances, which hold references to DOM nodes after the component is gone unless disconnected.

5. Subscriptions and event listeners

A listener registered on window captures the component's setter. Removing it in cleanup is the only reliable way to stop updates after unmount, and it also prevents duplicate handlers when the effect re-runs.

tsx
useEffect(() => { const onResize = () => setWidth(window.innerWidth); window.addEventListener("resize", onResize); return () => window.removeEventListener("resize", onResize); }, []);

For shared external sources, useSyncExternalStore is the modern replacement: it subscribes with a cleanup contract and avoids tearing during concurrent renders.

6. Promises started by an event handler

Navigation is the common case: a click starts a save, the user leaves, the promise resolves, and the setter runs against a dead tree.

tsx
async function onSave() { setSaving(true); await api.save(draft); // user may navigate away here setSaving(false); // harmless in React 18, still wasted work }

Disabling navigation is not a fix. Keep the state update, accept that it is a no-op after unmount, and move the actual persistence into a place that survives the component, such as a mutation cache or a form action. The warning is gone, but "fire and forget from a component" remains a design smell whenever the result matters.

Common Compilation/Runtime Mistakes & Version Gotchas

  • Adding if (!mounted) return everywhere. A boolean set in a cleanup is the ignore flag with extra renders. Use it locally, not as an app-wide pattern.
  • Aborting on every dependency change without handling it. Changing id aborts the previous request; if the rejection is reported, the UI flashes an error before the new data arrives.
  • Cleanup that does not match setup. Registering a listener inside a condition but removing it unconditionally throws or leaves a handler behind. Create and destroy in the same scope.
  • Assuming React 18 removed the race. It removed the warning. The dropped update, the wasted response, and the side effects after the setter all remain.
  • Fetching in render. A promise created during render restarts on every render and cannot be cleaned up. Fetch in an effect, a Server Component, or a data layer.
SymptomReal causeFix
double request in developmentStrictMode remountcorrect cleanup, not a guard flag
error toast on fast navigationabort treated as failurecheck signal.aborted
state resets when props changemissing dependencyadd id to the array
memory grows after routinglistener or interval not removedclear in cleanup

When a response looks wrong rather than late, paste it into the JSON formatter to confirm the shape before blaming the component, and use the text diff tool when comparing two versions of a component that behave differently.

The canonical references are the useEffect cleanup documentation for the contract, and the React 18 release notes for the decision to remove this warning. Together they explain why the correct fix looks like cancellation rather than suppression.

Official references

primary documentation

The React documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit React work — they run entirely in this browser tab, so nothing you paste leaves your device.

All React guides

More in React

All React guides

The guides filed next to this one in React, in library order.