React useEffect cleanup

I'm a full-stack developer from South Africa 🇿🇦. I love writing about JavaScript, HTML and CSS.
Search for a command to run...

I'm a full-stack developer from South Africa 🇿🇦. I love writing about JavaScript, HTML and CSS.
Glad you like it Sujeet
Thanks Dun
Thanks Adib, glad you enjoyed the article
Most of you know me for my consistency, a golden arrow in my blog series. I've written 1000 articles in 1008 days! Almost an article a day, and my honeymoon was the only holiday I ever took. I'm super proud of this achievement; it has been a fantasti...

It's not the first time I'll be talking about community. I think it's an essential aspect of any successful tool. This shows in my previous explorations of Astro, Medusa, and now Vendure as well. All these products thrive in a super open, welcoming, ...

The cool part about Vendure is how easy it is to set up and how abstract each layer is. Basically, we get the following elements: External database Server Worker Admin UI Frontend While this is amazing, it also brings a bit of complexity when it co...

The previous article looked at customizing Vendure on a data and process level. In this article, we'll look at customizing emails, as they are often a big part of a webshop system. We'll be looking at two different layers of customization for customi...

Even though Vendure is a pretty significant project out of the box, in some cases, we might want to go in and modify some elements to work to our specific use case. In this article, I'll take a high-level look at some elements we can customize within...

React's useEffect hook is a super hook to run side effects. You might be wondering what kind of side effects we could be talking about?
Let's set some examples.
It will be sufficient to use the hook as intended, so set an example in most cases.
useEffect(() => {
document.title = `The page is loaded`;
});
As we learned before we can set the dependency at which change this needs to fire:
useEffect(() => {
document.title = `The page ${title} is loaded`;
}, [title]);
The above code will only fire once the title variable is modified.
We can also opt to run only once on mount, by passing a empty array like this:
useEffect(() => {
// Only run once
document.title = `The page ${title} is loaded`;
}, []);
The hook comes with a cleanup function, which you might not always need, but it can come in handy.
To invoke the cleanup function you can simply add a return function like so:
useEffect(() => {
// Your effect
return () => {
// Cleanup
};
}, []);
The cleanup can prevent memory leaks and remove unwanted things. Some use-cases for this are:
Let's create an example where we have a function that adds something only after a specific time.
const [show, setShow] = useState(false);
useEffect(() => {
let timer = setTimeout(() => setShow(true), 3000);
}, []);
However, this will create a timeout in memory, so it would be best to clean this up.
For this let's add the cleanup function:
useEffect(() => {
let timer = setTimeout(() => setShow(true), 3000);
return () => {
clearTimeout(timer);
};
}, []);
Another example is, of course, a web socket call that keeps polling.
useEffect(() => {
let ws = new WebSocket('wss://ws.your-websocket/');
ws.onmessage = (msg) => {
// Do something with the message
};
return () => {
ws.close();
};
}, []);
We open the WebSocket connection, and we can use the cleanup function to close the connection.
Another thing you can use it for is tracking modal close events, for instance.
Let's say we have a modal in our code. Inside the modal component, we could add a useEffect that can fire on cleanup. This way, we capture every event.
A modal could be invoked by another component that cleaned up in the meantime, so there is no way of telling when the user closes it. (Or they close the application)
We can add tracking to fire with a cleanup effect when this happens.
useEffect(() => {
return () => {
trackModalClose();
};
}, []);
This way, we have a rock-solid method of tracking when the modal close should be invoked, and you can even add a check to see if the applications as closed or the modal close was invoked.
I hope you enjoyed this article on the cleanup function for the useEffect hook in React.
Let me know if you have any questions or other use-cases that would be worth exploring.
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter