Created
April 3, 2020 23:32
-
-
Save kentcdodds/b36572b6e9227207e6c71fd80e63f3b4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function useAbortController() { | |
const abortControllerRef = React.useRef() | |
const getAbortController = React.useCallback(() => { | |
if (!abortControllerRef.current) { | |
abortControllerRef.current = new AbortController() | |
} | |
return abortControllerRef.current | |
}, []) | |
React.useEffect(() => { | |
return () => getAbortController().abort() | |
}, [getAbortController]) | |
const getSignal = React.useCallback(() => getAbortController().signal, [ | |
getAbortController, | |
]) | |
return getSignal | |
} |
Ia had same implementation in typescript. Only difference if that I'm aborting with reason. I mostly use this in cases when I need to stop a flow on re-render.
import React from "react"
export function useAbortController() {
const abortControllerRef = React.useRef<AbortController | undefined>()
const getAbortController = React.useCallback(() => {
abortControllerRef.current =
abortControllerRef.current && !abortControllerRef.current.signal.aborted
? abortControllerRef.current
: new AbortController()
return abortControllerRef.current
}, [])
const getSignal = React.useCallback(() => {
return getAbortController().signal
}, [getAbortController])
React.useEffect(() => {
return () => {
getAbortController().abort("Re-render")
}
}, [getAbortController])
return getSignal
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Inspired by @charlestbell
abort()
anytime they want, not just on unmount.{ abort, signal }
instead of thegetSignal
function.null
checks onabortCtrlRef.current
instead offalsey
for perf (just because).Usage: