Kent C. Dodds recently floated this snippet around, a React Hook to easily work with the the AbortController
:
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;
}
💁♂️ The AbortController
is a Web API which allows you to cancel JavaScript promises.
Leave a comment