helderberto/use-is-mounted-ref
关于
🧹 React hooks that abort async work on unmount or when a newer call starts. Strict Mode safe, zero dependencies.
网站与应用开发实测星标增长
- 24小时
- 0
- 7天
- 正在收集历史
- 15天
- 正在收集历史
- 1个月
- 正在收集历史
各周期内的星标净变化,周期相互重叠,并非每日新增。缺失的测量保持空白。星标代表关注度,不代表软件质量。
README.md
原文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-ref
Requires 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
- API: behavior and examples per hook
- Recipes: listeners, timers, and more
- Migration: v1 to v2
- Changelog
Contributing
See CONTRIBUTING.md. Report bugs or suggest ideas in issues.
License
探索相关项目
加载中…