0

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Zenek Wiaderko
  • 392
  • 2
  • 14
  • Refer this: https://stackoverflow.com/questions/15886272/what-is-the-difference-between-a-function-call-and-function-reference – Devarshi Patel Jun 29 '21 at 13:04

1 Answers1

1

Well, I forgot that useEffect should return a function instead of just window.removeEventListener(...).

Zenek Wiaderko
  • 392
  • 2
  • 14