Memory Leaks? Clean Up?
A memory leak is memory that is no longer needed by a computer and is not released properly. What makes it so difficult to understand is that unlike other warnings that deal with something directly related to syntax, this one is about hardware.
We see this frequently as developers when we use a function within a useEffect and don’t clean it up. Which is exactly the example I’ll be using here to show you what it looks like and how to clean it up.
We’ll start off with two files. App.js and Clock.js in React. We’ll have a button that sets the ‘showClock’ state to either on or off. When it’s on, we’ll show text of the current time and update it every second. When it’s off, we’ll unmount the component.
import "./App.css";
import React, { useState } from "react";
import Clock from "./Clock";
const App = () => {
const [showClock, setShowClock] = useState(true);
return (
<>
<button onClick={() => setShowClock(!showClock)}>
{showClock ? "Clock ON" : "Clock OFF"}
</button>
{showClock && <Clock />}
</>
);
};
export default App;
import React, { useState, useEffect } from "react";
import format from "date-fns/format";
const Clock = () => {
const [time, setTime] = useState(new Date());
const formattedTime = format(time, "hh:mm:ss a");
useEffect(() => {
const interval = setInterval(() => {
console.log("tick");
setTime(new Date());
}, 1000);
// Dont' forget this clean up!!
return () => clearInterval(interval);
}, []);
return (
<>
<p>{formattedTime}</p>
</>
);
};
export default Clock;
We’ll focus on Clock.js to show memory leakage. When we mount the Clock component, we run our useEffect which is using the setInterval function to update our time
state. If you look at your console, you’ll notice that the word “tick” is printing. Now naturally, you’d think that if you clicked the ‘Clock OFF’ button, the printing will stop. And you’d be right.
Now if we remove the return () => clearInterval(interval)
and run through this process again, you’ll notice that “tick” is still printing but the component is no longer mounted — what’s going on here? That is memory leakage. Your device has stored this information and doesn’t know to remove it when the component unmounts. If you were to click the ‘Click On/Off’ button a few times, you’d see that the timer is updating more and more frequently. Thats why we need to add that clean up.
I know this is a very shortened explanation to memory leaks, garbage collection, and cleanups. If you’d like to visualize and checkout the hardware side of things, check this out.
So please don’t forget to clean up your code. And if you’re doing code reviews — look out for this stuff. As always, happy coding!