🍦 Cancel Properly HTTP Requests in React Hooks and avoid Memory Leaks 🚨
Tags: react, javascript, tutorial, showdev
Published: 2020-07-29 16:50:33

Hello guys ! 👋

Today, let's take a look at cancelling a web request with __fetch__ and __Abort Controller__ in React Hooks! 🤗

When we work with Fetch to manage data, we sometimes want to cancel the request (e.g. when we leave the current page, when we leave a modal, ...).

In the example below 👇, we __fetch__ the data to display when switching route. __But__, we leave the route/page before the fetch is completed.

![React hooks memory leaks 1](https://dev-to-uploads.s3.amazonaws.com/i/7p2coedr8hhtdltuzxu1.gif)
<figcaption>🚸 Demo 1/2</figcaption>

![React hooks memory leaks 2](https://dev-to-uploads.s3.amazonaws.com/i/4uoij0o2qmdlppeykeln.png)
<figcaption>🚸 Source code 2/2</figcaption>

We just saw a memory leak in action! 💪🏼 Let’s see why this error occurred, and what it exactly means.

❓ __WHY A MEMORY LEAK?__: We have a component that performs an asynchronous `fetch(url)` task, then updates the state of the component to display the elements, **BUT** we unmount the component before the request is even completed. The state of the unmounted component is updated (e.g. `setUsers`, `setState`), which follows a __memory leak__.

## 🚀 Let's use the new AbortController API !

__Abort Controller__ allows you to subscribe to one or more Web Requests with the ability to cancel them. 🔥

### Basics of AbortController

First of all, let's create a [new AbortController](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) object instance.

![Abort Controller API](https://dev-to-uploads.s3.amazonaws.com/i/fvipu2xkelip28hcfoqp.png)

Now, we can access to __`controller.signal`__.

> "The signal __`read-only`__ property of the `AbortController` interface returns an [AbortSignal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) object instance, which can be used to communicate with/abort a DOM request as desired." [MDN Source](https://developer.mozilla.org/en-US/docs/Web/API/AbortController)

Let's see how to use it 💪

![Abort fetch example 1](https://dev-to-uploads.s3.amazonaws.com/i/vlvi82bo5lk2nopqzn8z.png)

And finally, if we want to cancel the current request, just call __`abort()`__. Also, you can get `controller.signal.aborted` which is a `Boolean` that indicates whether the request(s) the signal is communicating with is/are aborted (true) or not (false).

![Abort fetch example 2](https://dev-to-uploads.s3.amazonaws.com/i/yswm5mktqv16v0tiio9e.png)

> ❗️ Note: When __`abort()`__ is called, the `fetch()` promise rejects with a __`DOMException`__ named `AbortError`.

Yeah, you just learned how to cancel a Web Request natively! 👏

## 🤩 Let's do this with React Hooks !

### ❌ __BEFORE__

Below is an example of a component that retrieves data in order to display them:

![Memory leak react hooks 1](https://dev-to-uploads.s3.amazonaws.com/i/466wuql2ru1fgkrc2snx.png)

If I leave the page too fast and the request is not finished: __MEMORY LEAK__

![Memory leak react hooks 2](https://dev-to-uploads.s3.amazonaws.com/i/daavdtgn3tvfeybcf3rq.png)

### ✅ __AFTER__

So let's `useEffect` to subscribe to our `fetch` request and to avoid memory leaks. We use the clean method of `useEffect` for calling `abort()` when our component unmount.

![No memory leaks react hooks](https://dev-to-uploads.s3.amazonaws.com/i/zsr8g1ecnburui4rkje9.png)

Now, no more memory leaks! 😍

![Example abort controller memory leaks](https://dev-to-uploads.s3.amazonaws.com/i/wqa6uud2tnz90okxiy1e.gif)

As always, feel free to reach out to me! 😉

You can check this demo on [abort-with-react-hooks.vercel.app](https://abort-with-react-hooks.vercel.app).
Also, here the source code of this article in this [gist](https://gist.github.com/viclafouch/91e4782d6831a2cf95def05eba80db11).

Cheers 🍻 🍻 🍻 

If you enjoyed this article you can follow me on [Twitter](https://twitter.com/TrustedSheriff "TrustedSheriff") or here on [dev.to](https://dev.to/viclafouch) where I regularly post bite size tips relating to HTML, CSS and JavaScript.

{% link https://dev.to/viclafouch/improve-your-productivity-with-snippets-of-javascript-on-the-chrome-devtools-3gfm %}

{% link https://dev.to/viclafouch/5-best-places-to-find-free-svg-css-icons-for-your-websites-41c5 %}