How to clean up subscriptions in react components using AbortController ?

Selvaganesh
2 min readMar 16, 2019

--

Warning: Can’t perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.

Warning: Can’t perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

One of the most common bug in react component where developers forget to clean up resources properly after unmount.

When you do any API call to fetch information you need to unsubscribe it properly.

So how do i unsubscribe an API call, the answer is just cancel your promise call. There are many to do this but here we will use AbortController

Abort Controller is a browser API which handles it easily without importing any module, let say your are using Fetch API to call request, pass the second argument with abortController signal instance. A single signal can be used to abort many fetches at once.

Here the code for Class & Hooks

Clean up in Class Components

Then to cleanup call abort() method from abortController instance inside componentWillUnmount()

Clean up in Hooks

To perform Data fetching, setting up a subscription you need to use useEffect API.

To clean up inside hooks return a cleanup function then call abort()

⚠️ UPDATE: Axios cancellation example added ⚠️

--

--