Skip to content

Instantly share code, notes, and snippets.

@thinkawitch
Forked from kentcdodds/abort-controller.js
Last active January 3, 2025 10:48
Show Gist options
  • Save thinkawitch/25f622448c899f2908e4735638b7dfcf to your computer and use it in GitHub Desktop.
Save thinkawitch/25f622448c899f2908e4735638b7dfcf to your computer and use it in GitHub Desktop.
React hook for AbortController with reset
function useAbortController(runEffect=false, runLayoutEffect=false) {
const acRef = useRef()
const getAbortController = useCallback(() => {
if (!acRef.current) {
acRef.current = new AbortController()
}
return acRef.current
}, []);
if (runEffect) {
useEffect(() => {
return () => {
acRef.current && acRef.current.abort()
}
}, [])
}
if (runLayoutEffect) {
useLayoutEffect(() => {
return () => {
acRef.current && acRef.current.abort()
}
}, [])
}
const resetAbortController = useCallback(() => {
acRef.current = new AbortController()
}, [])
return [getAbortController, resetAbortController]
}
@thinkawitch
Copy link
Author

@sagarpanchal You are right. My gist is a simple example with not changeable params of useAbortController.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment