DEV Community


How to cancel all subscriptions and asynchronous tasks in a useEffect cleanup function?

・1 min read

Even if the component is unmounted, useEffect will try to maintain contact with your data-fetching function. Because this is an anti-pattern that exposes your app to memory leaks, canceling your useEffect subscription optimizes your app.

When you don’t use you useEffect hook effectively and dont perform any cleanup technique then the error looks like in the console:

React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing….

To fix this problem, given below some example code, that might be help:

Example Code 1(Solution):
In the simple implementation example below, you’d use a flag (isSubscribed) to determine when to cancel your subscription. At the end of the effect, you’d make a call to clean up.

useEffect(() => {
// set a clean up flag
let isSubscribed = true;

// Try to communicate with sever API
.then(response => response.json())
.then(data => isSubscribed ? setState(prevState => ({
...prevState, user: data
})) : null)
.catch(error => {
if (isSubscribed) {
setState(prevState => ({

// cancel subscription to useEffect
return () => (isSubscribed = false)
}, []);

Example Code 2(Solution):
Read more:

Discussion (1)

insidewhy profile image

You should put your code samples between two sets of three backticks so that they show up correctly. You can also put the name of the programming language after the first set of backticks to enable syntax highlighting. This works in GitHub comments/readmes etc. also.