Skip to content

Instantly share code, notes, and snippets.

@kentcdodds
Created April 3, 2020 23:32
Show Gist options
  • Select an option

  • Save kentcdodds/b36572b6e9227207e6c71fd80e63f3b4 to your computer and use it in GitHub Desktop.

Select an option

Save kentcdodds/b36572b6e9227207e6c71fd80e63f3b4 to your computer and use it in GitHub Desktop.
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
}
@aovchinn
Copy link

aovchinn commented Mar 20, 2025

@rejhgadellaa that code has get signal() { return getAbortController().signal; } and then
const { abort, signal } = useAbortController();

I think it will call getter right away, why not just

const useAbortController = () => {
    const controllerRef = useRef<AbortController | null>(null);
    if (controllerRef.current === null) {
        controllerRef.current = new AbortController();
    }

    return {
        abort: controllerRef.current.abort,
        signal: controllerRef.current.signal,
    };
};

in versions above controller is created only when fetch is issued,
for example if there is some button that issues a request, we do not need abortController until it is pressed

@rejhgadellaa
Copy link

Hmm good point, I may have overdone it with the get signal() { ... } haha

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