Avoid Memory Leaks in your React App by canceling API calls
The most easily overlooked cause for memory leaks would be improper handling of API calls. Because calls to an API are asynchronous, it is possible for the component that initiated the task to be unmounted before the request finishes. This can happen for instance, when a user goes to another page while the current page has not finished loading.
To demonstrate, lets use a simple React app which has two components,
About and also a button to toggle between the two. The
Home component fetches blog post data from an API that we’ll setup using
json-server. We will also delay our server’s response time to 3 seconds, so that we have enough time to switch between the two components before the API request completes.
App.jsx we have a button which toggles the
isHome state and conditionally render either the
Home or the
Home component fetches the blog post data from our API server during initial render.
About component just contains some text to be rendered in the DOM.
We also need to add
json-server and configure it in our
package.json file with 3 seconds response delay.
"server": "json-server --watch db.json --port 3001 --delay 3000"
Now, if we run our project and click on the “About Page” button while loading is in progress, we will get a memory leak warning on the console.
A way to fix this issue is to cancel the API request when the
useEffect cleanup function is called. The preferred way of canceling a request would be to use the
AbortController as described in the Web API documentation. The
AbortController will allow us to abort the web request by passing the
AbortSignal to the
fetch method and then calling
abort before the component is unmounted.
We need make slight modifications to our
Home component to avoid the memory leak problem. We initialize a new
AbortController instance and pass the signal from the controller to our
fetch method as a signal property. Then we call
controller.abort on the return function of our
Now, if we try the same thing as before and switch to the
About component while loading is in progress the memory leak warning will not show up in the console.
Well that’s it for this article. Hope you enjoyed reading it. You can find the source code for the demo here.