xxxxxxxxxx
useEffect(() => {
// do someting when mount component
return function cleanup() {
// do something when unmount component
});
xxxxxxxxxx
useEffect(() => {
//your code goes here
return () => {
//your cleanup code codes here
};
},[]);
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. 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.
What is the solution??
Cleanup function:
Canceling a fetch request
There are different ways to cancel fetch request calls, we can use fetch AbortControlleror Axios AbortController.
This associates the controller and signal with the fetch request and lets us cancel it anytime using AbortController.abort():
xxxxxxxxxx
useEffect(() => {
//create a controller
let controller = new AbortController();
(async () => {
try {
const response = await fetch(API,
{
// connect the controller with the fetch request
signal: controller.signal,
},
);
// handle success
setList(await response.json());
// remove the controller
controller = null;
} catch (e) {
// Handle the error
}
})();
//aborts the request when the component umounts
return () => controller?.abort();
},[]);
xxxxxxxxxx
useEffect(() => {
function handleStatusChange(status) {
setIsOnline(status.isOnline);
}
ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
// Specify how to clean up after this effect:
return () => {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
};
});
xxxxxxxxxx
import React, { useEffect } from 'react';
function FriendStatus(props) {
useEffect(() => {
// do someting when mount component
return function cleanup() {
// do something when unmount component
};
});
}
xxxxxxxxxx
useEffect(() => {
let mounted = true;
setTimeout(() => {
if (mounted) {
setUsername('hello world');
}
}, 4000);
return () => mounted = false;
}, []);