I have a very simple function and very simple event listener in React. Here's the code:
const handleAutoplay = useCallback(() => {
console.log("test");
}, []);
useEffect(() => {
console.log("glo");
window.addEventListener("scroll", handleAutoplay);
return window.removeEventListener("scroll", handleAutoplay);
},[handleAutoplay])
The problem I have is, this event listener doesn't call the function it should. Nothing is happening. However, when I change the code to:
window.addEventListener("scroll", () => handleAutoplay());
it works like a charm. How come () => handleAutoplay()
is working when handleAutoplay
is not?
I tried it with and without useCallback
, so this is not an issue (AFAIK). Why is this happening? Any explanation? All examples on Stack Overflow and on the internet look exactly like the code I wrote. Am I missing something?