use-is-mounted-ref
v2.2.4
Published
🧹 React hooks that abort async work on unmount or when a newer call starts. Strict Mode safe, zero dependencies.
Maintainers
Readme
Why
Async work started from an event handler outlives the component. A request, listener or timer keeps running after unmount and updates stale state.
It also races itself. Type "ab" then "abc", and the slow "ab" response can land last and overwrite the right results.
These hooks hand you an AbortSignal that aborts at the right moment:
- On unmount, or when the next call starts
- Safe under React Strict Mode
- Typed, with hover docs in your editor
- Zero dependencies, under 400 B gzipped
Motivation
I built this library to fix one problem: updating state after a component unmounts. Before React 18, that logged this warning:
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.The first hook, useIsMountedRef, fixed it by skipping the update once the component was gone:
const isMountedRef = useIsMountedRef();
const load = async () => {
const user = await sdk.getUser();
if (isMountedRef.current) {
setUser(user);
}
};The library then grew to cover related problems:
- The guard skips the update, but the request keeps running.
useAbortSignalanduseAbortControllercancel the work itself. - Fast calls race, and a stale response can land last.
useLatestAbortSignalaborts the previous call.
Install
npm install use-is-mounted-refRequires React 16.8 or later. CI tests React 18 and 19.
Quick start
import { useAbortSignal } from 'use-is-mounted-ref';
function SaveButton({ data }) {
const signal = useAbortSignal();
const save = () =>
fetch('/api/save', { method: 'POST', body: JSON.stringify(data), signal }).catch((err) => {
if (err.name !== 'AbortError') throw err;
});
return <button onClick={save}>Save</button>;
}If the component unmounts mid-request, the request is aborted.
API
| Hook | Returns | Aborts / flips when | Use it for |
| ------------------------------------------------------------ | ------------------------------- | -------------------- | ---------------------------------- |
| useAbortSignal() | AbortSignal | Component unmounts | Most cases |
| useAbortController() | AbortController | Component unmounts | Calling abort() yourself |
| useLatestAbortSignal() | () => AbortSignal | Next call or unmount | Search as you type, latest wins |
| useIsMountedRef() | { readonly current: boolean } | Component unmounts | Promises that cannot take a signal |
These hooks do not abort when effect dependencies change. See Inside useEffect.
Docs
Contributing
See CONTRIBUTING.md. Report bugs or suggest ideas in issues.
