Why Should You Use Cleanup Functions in React’s useEffect Hook?
Tags: react, webdev, javascript, beginners
Published: 2022-11-09 03:17:22

## Cleanup functions in React’s useEffect hook — explained with examples.

f you are starting to learn React or already have some time using this library, surely, you have come across some errors or warnings related to asynchronous functions, especially using the hook `useEffect`.

When I was learning the functionality of this hook, I could not understand the reason to use the return in this function since in most cases it is not necessary to use it and React works perfectly well without it.

As I became more familiar with the way React works and the life cycle of the components, I began to notice that in many cases, it is too important to use the return in the hook `useEffect`, especially in the side effects.

## What are the side effects?
A side effect can be fetching data from a remote server, reading or writing to local storage, setting up event listeners, or setting up a subscription. These side effects can occur when a button is clicked, when a form is submitted, or when a component is mounted and unmounted.

React’s [`useEffect`](https://reactjs.org/docs/hooks-reference.html#useeffect) hook allows functional components to do things when a component is mounted or when some properties or states change. This hook also allows to clean up when the component is unmounted.

Why clean up side effects?
Handling side effects in React is a task of medium complexity. However, from time to time, you may have difficulties at the intersection of the component lifecycle (initial rendering, assembly, usage, disassembly) and the side-effect lifecycle (started, in progress, complete).

One such difficulty is when a side effect completes and attempts to update the state of an already disassembled component.

This causes a React warning like this:

![Error react](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8d3mjk5zknziuugvvh89.png)

Memory leaks in React applications are mainly the result of not canceling subscriptions made when a component was mounted before the component is unmounted.

They cause many problems, including:

* Affects the performance of the project by reducing the amount of memory available.
* Slowing down the application.
* System crashes.

Therefore, it’s necessary to eliminate memory leak problems.

What is the `useEffect` cleanup function?
It is a function of the useEffect hook that allows us to stop side effects that no longer need to be executed before our component is unmounted.

`useEffect` is built in such a way that we can return a function inside it and this return function is where the cleanup happens.

For example, Component A requests the API to get a list of products, but while making that asynchronous request, Component A is removed from the DOM (it’s unmounted). There is no need to complete that asynchronous request.

So as a cleanup method to improve your application, you can clean up (cancel) the asynchronous request so that it’s not completed.

[Cleanup function of useEffect](https://reactjs.org/docs/hooks-effect.html#effects-without-cleanup):

``` javascript
useEffect(() => {
  // Your effect
  return () => {
    // Cleanup
  }
}, [input])
```

## Cleaning up an effect

### Canceling a fetch request

There are different ways to cancel fetch request calls, we can use fetch [AbortControlleror](https://javascript.info/fetch-abort#:~:text=To%20be%20able%20to%20cancel,how%20to%20work%20with%20AbortController%20.) Axios [AbortController](https://axios-http.com/docs/cancellation).

To use `AbortController`, we must create a controller using the `AbortController()` constructor. Then, when our fetch request initiates, we pass `AbortSignal` as an option inside the request’s `options` object.

This associates the controller and signal with the fetch request and lets us cancel it anytime using `AbortController.abort()`:

{% embed https://gist.github.com/ljaviertovar/599cccd27439a2df4665041e8ea4962d %}

{% embed https://gist.github.com/ljaviertovar/0bf9218f550d4f17863dbb16ef8e38dc %}

## Cleaning up Timeouts

When using [setTimeout](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout)(callback, time) timer functions, we can clear them on unmount by using the special `clearTimeout(timerId)` function.

{% embed https://gist.github.com/ljaviertovar/6583729ae8f2d290863fbe1c9696b2a6 %}

## Cleaning up Intervals

Like the Timeouts, the [setIntervals](https://developer.mozilla.org/en-US/docs/Web/API/setInterval)(callback, time)have a special function to clean them up with `clearInterval(intervalId)` function.

{% embed https://gist.github.com/ljaviertovar/28f6597561d91f898599c96f56dfbbff %}

## Cleaning up Event Listeners

Clean up Listeners happens via [window.removeEventListener](https://developer.mozilla.org/es/docs/Web/API/EventTarget/removeEventListener). The `removeEventListener` call must reference the same function in the `removeEventListener`call to remove the listener correctly.

{% embed https://gist.github.com/ljaviertovar/c702c817ced8642f15ee4ec8bd93fa4a %}

## Cleaning up Web Sockets

When you create a [WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) connection, you can close it in the cleanup `socket.close()` function.

{% embed https://gist.github.com/ljaviertovar/9f1bbf59f980512d77df73115a0a4931 %}



## Conclusion

We have learned that some side effects require cleanup to avoid memory leaks and unnecessary and unwanted behaviors. We must learn when and how to use the cleanup function of the useEffecthook to avoid these problems and optimize applications.

I recommend cleaning up asynchronous effects when the component is unmounted. Also, if the asynchronous side effect depends on the prop or state values then consider also cleaning them up when the component is updated.

I hope you found this article useful and that you can now use the cleanup feature correctly.

---

**Read more:**

- [How to build an autocomplete search component in React and TypeScript](https://dev.to/ljaviertovar/autocomplete-search-component-with-react-and-typescript-2lj3)

- [How to hide your API keys and tokens in React to protect your application](https://dev.to/ljaviertovar/how-to-hide-your-api-keys-and-tokens-in-react-to-protect-your-application-1dmc)

**Want to Connect?**
Love connecting with friends all around the world on [Twitter](https://twitter.com/ljaviertovar).