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.

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:
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
AbortControllerand ignoreAbortErrordeliberately. - 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.
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 version | Warning | What still happens |
|---|---|---|
| 16 and 17 | printed in development | dropped update, leaked work |
| 18 | removed | dropped update, leaked work |
| 19 | removed | dropped update, leaked work |
| StrictMode, dev | never reliable | effects mount twice on purpose |
Key Comparison Table
| Approach | Cancels network | Code cost | Correct when |
|---|---|---|---|
AbortController | yes | a few lines per effect | fetch or any abort-aware API |
ignore flag | no, discards result | three lines | third-party promise without abort |
| Data library keyed by id | yes, per key | a dependency | many components fetch similar data |
| Move fetch to the parent | no | architectural change | children mount and unmount often |
useSyncExternalStore | not applicable | a store per source | external 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.
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.
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.
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.
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.
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.
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) returneverywhere. 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
idaborts 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.
| Symptom | Real cause | Fix |
|---|---|---|
| double request in development | StrictMode remount | correct cleanup, not a guard flag |
| error toast on fast navigation | abort treated as failure | check signal.aborted |
| state resets when props change | missing dependency | add id to the array |
| memory grows after routing | listener or interval not removed | clear 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 documentationThe React documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit React work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related React guides
All React guidesReact 19: Support for defaultProps will be removed
React 19 ignores defaultProps on function components, so a default becomes undefined. Move defaults into the parameter list and handle null honestly.
React: Each child in a list should have a unique key prop
Keys tell React which item is which between renders. Use stable ids, avoid index keys and put the key on the mapped element, not on a wrapper.
react-hook-form with zod 4: resolver type errors after the upgrade
Zod 4 split input from output and resolvers v5 re-typed Resolver. Drop the generic, or pass all three, and the errors disappear.
React Profiler API: Measuring Render Timings and Identifying Wasted Re-Renders
actualDuration versus baseDuration, phase names that tell you who triggered a commit, and how to ship the numbers without flooding a backend.
More in React
All React guidesThe guides filed next to this one in React, in library order.