I am new to React and I am trying to understand how this piece of code works. I was following a tutorial and the author's code can be found on GitHub: https://github.com/judygab/web-dev-projects/blob/main/personal-portfolio/src/components/NavBar.js
I don't understand how this hook useEffect
can continuously run even though it has an empty dependency array?
To my understanding, when you put an empty array as the second parameter, it will only fire off once, when the component is rendered to the DOM.
What exactly is happening so that it fires every time you scroll upon and down the page. I suspect that the definition I have is either not fully complete or the window.addEventListener
is continuously adding/removing from the DOM.
useEffect(() => {
const onScroll = () => {
if (window.scrollY > 50) {
setScrolled(true);
} else {
setScrolled(false);
}
}
window.addEventListener("scroll", onScroll);
return () => {
window.removeEventListener("scroll", onScroll);
}
}, [])
I have tried logging messages to the console at different points in the code but I am not sure why they would be firing continuously. Any explanation of what's going on would be greatly appreciated!