'Why do we add eventListeners in useEffect hook

Can anyone please give me a clear explanation on why we add event listeners in useEffect? It always confuses me. I was reading a blog on how to make a navbar fixed on scroll and I saw that the person added the event listener in the useEffect hook. Link to the blog Change Navbar Style With The Scroll In A Next.Js Website

const [clientWindowHeight, setClientWindowHeight] = useState("");

const handleScroll = () => {
     setClientWindowHeight(window.scrollY);
};

useEffect(() => {
    window.addEventListener("scroll", handleScroll); 
    return () => window.removeEventListener("scroll", handleScroll);
});


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source