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
}
@schichulin

Copy link
Copy Markdown

Amazing 😍

@Krisztiaan

Copy link
Copy Markdown

The first useCallback is unnecessary

@kentcdodds

Copy link
Copy Markdown
Author

It's not

@Krisztiaan

Copy link
Copy Markdown

Sorry, should have been a bit more verbose than that.
Since it doesn't have any dependencies, the returned function will never actually change by reference.
This would mean that neither the useEffect's, nor the other useCallback's dependency array really ever changes, the dependency array might as well be [], in which case the first useCallback is unnecessary, because it's reference is never again relevant to anything. You actually have a good post about When to useMemo and useCallback, with a similar scenario as one of the points.

I'm curious what you think about the following versions, and if you see any caveats in just going with the first one:

function useAbortController() {
  const abortControllerRef = React.useRef(new AbortController())

  React.useEffect(() => () => abortControllerRef.current.abort(), [])

  return abortControllerRef.current.signal
}
function useAbortController() {
  const abortControllerRef = React.useRef<AbortController>()
  const getAbortController = () => {
    return (abortControllerRef.current = abortControllerRef.current || new AbortController())
  }

  React.useEffect(() => {
    return () => getAbortController().abort()
  }, [])

  const getSignal = React.useCallback(() => getAbortController().signal, [])

  return getSignal
}

@kentcdodds

Copy link
Copy Markdown
Author

To do that, you would have to ignore the react-hooks/exhaustive-deps eslint rule when there's really not issue doing so. In this case we are adding complexity by including those hooks, but we're getting the benefit of ensuring that if anyone changes this code they don't miss dependencies.

The issue with your first example is that you'd create a new AbortController in every render.

The way my code works, you only create one when you need one.

@Krisztiaan

Copy link
Copy Markdown

Thank you for engaging with me on this random piece of discussion.

The original code still creates an AbortController, even if it's never "used", for the useEffect cleanup.

Removing the callback, and the unintended instantiation, this seems slightly less readable but functionally more fitting to presumed intention, with no loose ends.

function useAbortController() {
  const abortControllerRef = React.useRef<AbortController>()

  React.useEffect(() => {
    return () => abortControllerRef.current?.abort()
  }, [])

  const getSignal = React.useCallback(() => {
    if (!abortControllerRef.current) {
      abortControllerRef.current = new AbortController()
    }
    return abortControllerRef.current.signal
  }, [])

  return getSignal
}

@kentcdodds

Copy link
Copy Markdown
Author

Solid 👍👍

@PerryRylance

Copy link
Copy Markdown

Hello folks, could someone kindly show me how this works in practise?

I'm currently doing this with a ref, this looks more elegant though

@nzkks

nzkks commented Jul 21, 2023

Copy link
Copy Markdown

Whoever found above gist first before Kent's own tweet, use the above hook like below. Directly copied from that tweet.

const getSignal = useAbortController()

// in an effect
fetch('/thing', {signal: getSignal()})

@webgodo

webgodo commented Aug 3, 2023

Copy link
Copy Markdown

I use it this way, but it raises error: Failed to execute 'fetch' on 'Window': The user aborted a request.

  const getSignal = useAbortController();
  const [data, setData] = useState();

  const doFetch = async () => {
    const signal = getSignal();
    const response = await fetch("https://codesandbox.io", { signal });
    const result = await response.body;

    setData(result);
  };

  useEffect(() => {
    doFetch()
  }, []);

How to solve?

@charlestbell

Copy link
Copy Markdown

How do you manually call abort() from this?

@charlestbell

charlestbell commented Aug 8, 2023

Copy link
Copy Markdown

Here is my manually controlled abortController I use to allow users to cancel an upload in React Native

function useAbortController() {
  const abortControllerRef = useRef();
  const getAbortController = useCallback(() => {
    console.log('getAbortController', abortControllerRef.current);
    if (!abortControllerRef.current) {
      abortControllerRef.current = new AbortController();
    }
    return abortControllerRef.current;
  }, []);

  const abortSignal = useCallback(() => {
    if (abortControllerRef.current) {
      abortControllerRef.current.abort();
 
      abortControllerRef.current = null;      // Resets it for next time
    }
  }, []);

  const getSignal = useCallback(
    () => getAbortController().signal,
    [getAbortController]
  );

  return { getSignal, abortSignal };
}

@rejhgadellaa

rejhgadellaa commented Jul 25, 2024

Copy link
Copy Markdown

Inspired by @charlestbell

  • Leave control to the user of the hook to abort() anytime they want, not just on unmount.
  • Returns a (memoized) object that resembles the AbortController API: { abort, signal } instead of the getSignal function.
  • Strict null checks on abortCtrlRef.current instead of falsey for perf (just because).
function useAbortController() {

  const abortCtrlRef = useRef( null );

  const getAbortController = useCallback(
    () => {
      if ( abortCtrlRef.current === null ) abortCtrlRef.current = new AbortController();
      return abortCtrlRef.current;
    },
    []
  );

  const abort = useCallback(
    () => {
      if ( abortCtrlRef.current !== null ) {
        abortCtrlRef.current.abort();
        abortCtrlRef.current = null;
      }
    },
    []
  );

  return useMemo(
    () => ({
      get signal() { return getAbortController().signal; },
      abort,
    }),
    [ getAbortController, abort ]
  );

}

Usage:

function MyComponent( props ) {

  // { abort, signal } just like a real AbortController
  const { abort, signal } = useAbortController();

  // Some useEffect or other thing you need to be able to abort
  useEffect(() => fetch( url, { signal } ), [ signal ]);

  // The user of the hook can abort whenever they please.
  useEffect(() => () => abort(), [ abort ]);

}

@aovchinn

aovchinn commented Mar 20, 2025

Copy link
Copy Markdown

@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
Copy Markdown

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