useEffect Cleanup Functions

As a Vue.js fanboy, I've largely ignored what's been going on in the React ecosystem for far too many years, and so now I find myself cramming every possible React tutorial under the sun to get a better understanding of how it works.
Today I have been working my way through Ali Spittel's React.js Coding Challenges over on LinkedIn Learning to put what I've learned so far to the test. The challenge in question was to add a double-click listener to the window when a toggle button is clicked, then remove it again once the toggle button is clicked again.
Once I'd finished the task, I watch the solution and discovered that you can return a function from inside the setup function of a useEffect hook:
import { useEffect } from "react";
export default function windowEvent() {
useEffect(() => {
const handleDblClick = () => alert("mouse pressed");
window.addEventListener("dblclick", handleDblClick);
return () => window.removeEventListener("dblclick", handleDblClick);
});
}
I'd never seen this before, but it turns out that this method is known as a clean-up function, which is executed when the component is re-rendered, before running the setup method again.




