Search code examples
javascriptreactjsscrolldom-events

Event listener is not calling the function when it's passed as reference


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?


Solution

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

    Instead of:

    useEffect(() => {
          console.log("glo");
          window.addEventListener("scroll", handleAutoplay);
          return window.removeEventListener("scroll", handleAutoplay);
        },[handleAutoplay])
    

    I Should have:

    useEffect(() => {
      console.log("glo");
      window.addEventListener("scroll", handleAutoplay);
      return () => window.removeEventListener("scroll", handleAutoplay);
    },[handleAutoplay])
    

    The difference is what useEffect is returning.