Simply put, a memory leak is said to occur whenever inaccessible or unreferenced data exists in memory.

According to Wikipedia, a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in a way that memory that is no longer needed is not released. A memory leak may also happen when an object is stored in memory but cannot be accessed by the running code.

Memory leaks in React applications are primarily a result of not canceling subscriptions made when a component was mounted before the component gets unmounted. These subscriptions could be a:

  • DOM Event Listener
  • WebSocket Subscription
  • Request to an API

In this article, we will focus on how to avoid memory leaks on a DOM Event Listener, but the process is pretty similar for a WebSocket Subscription.

Basically, when we add an Event Listener in React, we need to remove them in order to avoid memory leaks.

Using Class Components

Let's take a look at how we can do this using class components:

As seen above, we create the Event Listener in componentDidMount and removed it in componentWillUnMount.

Using Functional Components

We can achieve the same functionality in functional components using the useEffect hook to add and remove the Event Listener as follows:

The empty [ ] as dependency list makes sure our useEffect is called only once after the first render.

To allow us to clean up things, useEffect allows us to return a clean-up function from our callback. React will call this clean-up callback before it calls our useEffect callback the next time like when a dependency changes.

Also, React will call this clean-up when the component unmounts. Thus, we remove the Event Listener in the clean-up call back.


In this article, we looked at memory leaks that occur when we use DOM Event Listeners and how to avoid them. We also state that the process is pretty similar for memory leaks due to WebSocket subscriptions.

However, for memory leaks due to “Request to an API”, the process is a little bit different and requires something called “AbortControllers”. You can read more about it here.

If you like this article, please leave a few claps (or a lot) and make sure to follow me on Medium if you are not already. You can also subscribe to get an email whenever I publish.