Skip to Content

useAbortableEffect

Exports Size
loading...
Gzip Size
loading...
Brotli Size
Source Code
View on GitHub
Docs
Edit this page

useEffect that gives you an AbortSignal .

Usage

import { useAbortableEffect } from 'foxact/use-abortable-effect'; function Component() { useAbortableEffect(signal => { item.addEventListener('event', () => { // ... }, { signal }) }, [item]); }
// before useEffect(() => { let isCancelled = false; someAsyncStuff().then(data => { if (!isCancelled) { setData(data); } }); return () => { isCancelled = true; }; }, [dataKey]); // after useAbortableEffect((signal) => { someAsyncStuff().then(data => { if (!signal.aborted) { setData(data); } }); }, [dataKey]);

You can also pass the signal to your async function if it supports AbortSignal:

useAbortableEffect((signal) => { someAsyncStuff({ signal }) .then(data => { if (!signal.aborted) { setData(data); } }) .catch(error => { if (error.name === 'AbortError') return setError(error); }); }, [dataKey]);

Note that eslint-plugin-react-hooks requires extra configuration in order to check dependency array for third-party hooks:

.eslintrc.json
{ "rules": { "react-hooks/exhaustive-deps": [ "warn", { "additionalHooks": "useAbortableEffect" } ] } }

But if you do not want to configure it, foxact/use-abortable-effect also provides another named export useEffect as an alias of useAbortableEffect:

- import { useEffect } from 'react'; + import { useEffect } from 'foxact/use-abortable-effect';