🌐
j-labs
j-labs.pl › home › tech blog › how to use the useeffect hook with the abortcontroller
AbortController in React. How to use the useEffect hook with the AbortControl? | j‑labs
December 9, 2025 - In the example above, we have created an instance of AbortController and obtained the associated AbortSignal within the useEffect hook. We have initiated the asynchronous operation, fetchData(), passing the signal as an argument. If the component unmounts or if a dependency changes, the cleanup function returned by useEffect is triggered.
🌐
Medium
eminfurkan.medium.com › managing-asynchronous-operations-with-abortcontroller-in-react-e9bec3565ec8
Managing Asynchronous Operations with AbortController in React | by Furkan Tezeren | Medium
July 30, 2023 - We also clean up by canceling the request using abortController.abort() when the component unmounts. ... import { useEffect, useState } from 'react'; function MyComponent() { const [data, setData] = useState(null); const controller = new AbortController(); const signal = controller.signal; useEffect(() => { async function fetchData() { try { const response = await fetch('https://my-api.com/endpoint', { signal }); const json = await response.json(); setData(json); } catch (error) { if (error.name === 'AbortError') { console.log('Fetching data was aborted'); } else { console.error(error); } } } fetchData(); return () => { controller.abort(); }; }, []); return ( <div> {data ?
🌐
Close
making.close.com › posts › introducting-use-abortable-effect-react-hook
Introducing useAbortableEffect: a simple React hook for running abortable effects | The Making of Close
June 18, 2020 - // Regular React effect hook. useEffect(() => { // do something return () => { /* cleanup */ }; }, [deps]); // An abortable effect hook. const abortControllerRef = useAbortableEffect( (abortSignal) => { // do something return (abortController) => { /* do cleanup, you should probably abort */ ...
🌐
Medium
medium.com › @icjoseph › using-react-to-understand-abort-controllers-eb10654485df
Using React to understand Abort Controllers | by Joseph Chamochumbi | Medium
November 18, 2022 - And there’s the AbortController, which fits both cases. You’d use this in a React useEffect hook like this:
🌐
Academind
academind.com › tutorials › useeffect-abort-http-requests
useEffect(), Http Requests & Aborting
July 9, 2020 - We can change our code that uses the isActive variable, to use AbortController by implementing the above mentioned steps: useEffect(() => { const abortCtrl = new AbortController(); const opts = { signal: abortCtrl.signal }; fetch('https://jsonplaceholder.typicode.com/todos/1', opts) .then((response) => response.json()) .then((data) => setTodo(data)) .catch((error) => console.log(error.message)); return () => abortCtrl.abort(); }, []); When any request is cancelled using the AbortController object, an AbortError is thrown.
🌐
DEV Community
dev.to › pallymore › clean-up-async-requests-in-useeffect-hooks-90h
Clean Up Async Requests in `useEffect` Hooks - DEV Community
October 12, 2019 - When is if(!isCancelled) inside the useEffect is being checked? ... Sr. FE Dev @ AWS - comments/blogs are my own. ... Sr. FE Dev @ AWS ... In your case using the flag is not going to work. If you are using fetch to make requests you can use AbortController (just provide the signal to the thunk action)
Find elsewhere
Top answer
1 of 1
7

Using an abort controller, in its rawest form:

const controller = new AbortController();
const { signal } = controller;
...

fetch(url, { signal });

...
// abort
controller.abort();

To abort an in-flight fetch in effect hook

useEffect(() => {
  const controller = new AbortController();
  const { signal } = controller;
  fetch(url, { signal });

  return () => {
    controller.abort(); // abort on unmount for cleanup
  };
}, []);

I found this article very informative when I needed to develop a way to cancel fetch requests.

The signal needs to be added to the fetch requests options object. You can also define the async fetchData function inside the effect (this is normal), so it's all enclosed in the effect hook's callback scope.

export const useMovieDetailsFetch = (movieId) => {
  const [state, setState] = useState({})
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(false)

  useEffect(() => {
    const controller = new AbortController();
    const { signal } = controller;

    const fetchData = async () => {
      setError(false);
      setLoading(true);

      try {
        const movieDetailsEndpoint =
          `${MOVIE_API_URL}movie/${movieId}?api_key=${MOVIE_KEY}`;
        const result =
          await (await fetch(movieDetailsEndpoint, { signal })).json();
        const creditsEndpoint =
          `${MOVIE_API_URL}movie/${movieId}/credits?api_key=${MOVIE_KEY}`;
        const creditsResult =
          await (await fetch(creditsEndpoint, { signal })).json();
        // Filtring in crew for directors only
        const movieDirectors = creditsResult.crew.filter(
          (member) => member.job === 'Director'
        );

        setState({
          ...result,
          movieDirectors,
          actors: creditsResult.cast,
        });
      } catch (error) {
        setError(true);
      }
      setLoading(false);
    }

    fetchData();

    return () => controller.abort();
  }, [movieId]);

  return [state, loading, error];
}
🌐
DEV Community
dev.to › bil › using-abortcontroller-with-react-hooks-and-typescript-to-cancel-window-fetch-requests-1md4
Using AbortController (with React Hooks and TypeScript) to cancel window.fetch requests - DEV Community
March 27, 2019 - // src/hooks/useProfileInformation.jsx import {useState, useEffect} from 'react' export function useProfileInformation({accessToken}) { const [profileInfo, setProfileInfo] = useState(null) useEffect(() => { const abortController = new AbortController() window .fetch('https://api.example.com/v1/me', { headers: {Authorization: `Bearer ${accessToken}`}, method: 'GET', mode: 'cors', signal: abortController.signal, }) .then(res => res.json()) .then(res => setProfileInfo(res.profileInfo)) return function cancel() { abortController.abort() } }, [accessToken]) return profileInfo } // src/app.jsx impor
🌐
Wanago
wanago.io › home › using abortcontroller to deal with race conditions in react
Using AbortController to deal with race conditions in React
April 11, 2022 - If we do that, abortController.abort() aborts multiple requests. The above also fixes the issue we’ve had with the race conditions. The user opens /posts/1 to see the first post, we start fetching the post with id 1, Not waiting for the first post, the user changes the page to /posts/2, the useEffect cleans after the previous post and runs abortController.abort(), we start fetching the post with id 2, the post loads without issues and is available almost immediately, The first post never finishes loading because we’ve already aborted the first request.
🌐
LogRocket
blog.logrocket.com › home › understanding react’s useeffect cleanup function
Understanding React’s useEffect cleanup function - LogRocket Blog
December 16, 2024 - This associates the controller and signal with the fetch request and lets us cancel it anytime using AbortController.abort(): useEffect(() => { const controller = new AbortController(); const signal = controller.signal; fetch(API, { signal: signal, }) .then((response) => response.json()) .then((response) => { // handle success }); return () => { // cancel the request before component unmounts controller.abort(); }; }, []);
🌐
GitHub
github.com › closeio › use-abortable-effect
GitHub - closeio/use-abortable-effect: Super simple React hook for running abortable effects based on the AbortController API.
useEffect(() => { // do something return () => { /* cleanup */ }; }, [deps]); const abortControllerRef = useAbortableEffect( (abortSignal) => { // do something return (abortController) => { /* do cleanup, you should probably abort */ }; }, [deps], );
Author   closeio
🌐
DEV Community
dev.to › leapcell › do-you-really-know-abortcontroller-3628
Do You Really Know AbortController? - DEV Community
January 16, 2025 - For older browsers, consider adding a polyfill to support AbortController. In React, effects can inadvertently run in parallel if the component updates before a previous asynchronous task completes: function FooComponent({ something }) { useEffect(async () => { const data = await fetch(url + something); // Handle the data }, [something]); return <>...</>; } To avoid such issues, use AbortController to cancel previous tasks: function FooComponent({ something }) { useEffect(() => { const controller = new AbortController(); const { signal } = controller; (async () => { const data = await fetch(ur
🌐
LogRocket
blog.logrocket.com › home › the complete guide to the abortcontroller api
The complete guide to the AbortController API - LogRocket Blog
March 12, 2025 - Using AbortController, it looks like this: useEffect(() => { const controller = new AbortController(); const { signal } = controller; // Define all your handler functions const handleMouseMove = (e) => { /* update state */ }; const handleKeyPress = (e) => { /* update state */ }; const handleScroll = () => { /* update state */ }; const handleResize = () => { /* update state */ }; // Add all the listeners with the signal document.addEventListener('mousemove', handleMouseMove, { signal }); document.addEventListener('keydown', handleKeyPress, { signal }); window.addEventListener('scroll', handleScroll, { signal }); window.addEventListener('resize', handleResize, { signal }); // Just one line for cleanup!
🌐
Whitespectre
whitespectre.com › ideas › abortcontroller-api-javascript
AbortController API: A Modern Approach to JavaScript Lifecycle Events | Whitespectre
April 19, 2023 - Now let’s see the same example using AbortController: const videoContainerRef = useRef<HTMLDivElement>(null); const [loadVideo, setLoadVideo] = useState(false); useEffect(() => { const controller = new AbortController(); function onScroll(e) { const rect = videoContainerRef.current?.getBoundingClientRect(); if (rect && rect.top < window.innerHeight) { setLoadVideo(true); controller.abort(); } } window.addEventListener('scroll', onScroll, { signal: controller.signal }); return () => controller.abort(); }, []); While at first glance there’s not much of a difference between these two approaches, once we start adding up event handlers, it becomes much easier to just use AbortController, saving us from declaring a function dedicated to removing listeners.
🌐
Web Dev Simplified
blog.webdevsimplified.com › 2025-06 › advanced-abort-controller
These Advanced AbortController Features Are Amazing
June 23, 2025 - If you pass the signal property with the AbortController’s signal, then when you call controller.abort(), it will automatically remove the event listener as if you called removeEventListener. This is especially useful in frameworks like React where you want to clean up event listeners from useEffect, or when you have many event listeners you want to remove at the same time.
🌐
GitHub
github.com › facebook › react › issues › 25284
Bug: React.StrictMode causes AbortController to cancel · Issue #25284 · facebook/react
September 16, 2022 - const useAbortController = (abortControllerProp, shouldAutoRestart = false) => { const abortController = useRef(abortControllerProp || initAbortController()); useEffect(() => { if (shouldAutoRestart && abortController.current.signal.aborted) { abortController.current = initAbortController(); } }, [abortController.current.signal.aborted, shouldAutoRestart]); useEffect(() => () => abortController.current.abort(), []); return abortController.current; }; The "echoed" rendering of the component causes the the controller to go from aborted false -> true.
Author   EdmundsEcho
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › API › AbortController
AbortController - Web APIs | MDN
September 17, 2025 - The AbortController interface represents a controller object that allows you to abort one or more Web requests as and when desired.