React: useEffect Lifecycle & Cleanup

Cosmin Mihalache
3 min readJul 4, 2022

--

React useEffect Hook

In class components, we have lifecycle methods to perform actions at a certain stage of our component’s lifecycle. In order for us to do something similar and perform side effects in our functional components, the React team created the useEffect hook.

🎈In order to use useEffect hook, first we have to import it.

import { useEffect } from "react";

🎈To use it it has to be called inside component

useEffect(() => {

});

🎈As the second argument to our useEffect hook we can set an array. Inside this array, we can pass the dependencies that the useEffect hook will track. By passing over an array of dependencies, the useEffect Hook will only execute if one of these dependencies are changed.
If you pass an empty array to the useEffect Hook, it will only be executed once after rendering.

useEffect(() => {

},[]);

useEffect Lifecycle

componentDidMount with useEffect

useEffect(() => {
// Inside this callback function we perform our side effects.
});

This is how componentDidMount can be performed inside a functional component, by not passing any array as second argument.

componentDidUpdate with useEffect

useEffect(() => {
// Inside this callback function we perform our side effects.
},[dependency]);

In order to perform componentDidUpdate in functional component pass an empty array as second parameter.

On the initial mount of the component, useEffect runs the callback function without checking if the dependency has changed or not.

Then, during the lifetime of the component when the state changes and the component updates, the dependencies array is checked to see if it changed since the recent update.

componentWillUnmount with useEffect

useEffect(() => {
window.addEventListener("mousemove", () => {});
return () => {
window.removeEventListener("mousemove", () => {})
}
}, []);

To use equivalent of componentWillUnmount in useEffect, all we need to do is to return a function inside the calback function of the useEffect.

🗑Cleanup useEffect

The useEffect cleanup function in React, plays a role in avoiding unwanted effects such as memory leaks. Hence, it is a method by which we can optimize the performance of our applications

The useEffect hook is built in such a way that we can return a function inside it, where the cleanup take place.

🗑 Cleanup a fetch request

Using AbortController

To use this method, we must to create a controller using AbortController() constructor.

Next, on fetch request starts, AbortSignal has to be passed as an option inside request option object. Hence, we pair controller with the fetch request, giving the option to cancel anytime using AbortController.abort()

>useEffect(() => {
const controller = new AbortController();
const signal = controller.signal;

fetch(API, {
signal: signal
})
.then((response) => response.json())
.then((response) => {
// handle success
});
return () => {
// cancel the request before component unmounts
controller.abort();
};
}, []);

🗑 Cleanup axios request

In Axios can be done using Axios cancel token.

Hence, we need to store the CancelToken.source() in a constant named source, pass the token as an Axios option and cancel the Axios request using source.cancel().

useEffect(() => {
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
axios
.get(API, {
cancelToken: source.token
})
.catch((err) => {
if (axios.isCancel(err)) {
console.log('successfully aborted');
} else {
// handle error
}
});
return () => {
// cancel the request before component unmounts
source.cancel();
};
}, []);

According to React’s official documentation, “React performs the cleanup when the component unmounts. However… effects run for every render and not just once. This is why React also cleans up effects from the previous render before running the effects next time.”

The cleanup is commonly used to cancel all subscriptions made and cancel fetch requests.

Happy coding💻

--

--

Cosmin Mihalache
Cosmin Mihalache

Written by Cosmin Mihalache

Front end developer based in Romania, specialized in ReactJS, focused on developing clean, maintainable, and scalable web applications.

No responses yet