I understand React recommends to add and remove event listeners every time when App is updated, however, I realized below code works even though the event listener was removed (at least in my understandings):
function App() {
const [posY, setPosY] = useState(0);
useEffect(() => {
const handleScroll = (e) => window.requestAnimationFrame(()=>{
setPosY(window.pageYOffset);
});
window.addEventListener("scroll", handleScroll);
return () => window.removeEventListener("scroll", handleScroll);
}, []);
return <div>{posY}</div>;
}
Can anyone help me understand why it still listens to scroll events? I thought it won't work because:
- The event listener was removed by this line,
return () => window.removeEventListener("scroll", handleScroll);
- The
useEffect
hook runs only once at the very beginning due to the blank array setPosY(window.pageYOffset)
invoke a new update/render, and the nextApp()
update will skipuseEffect
.
Are above three statements correct? It seems that I don't fully understand what is going on here.