0

I have a question regarding Event Listeners inside React Components. For window events I always use the return function inside the useEffect, but for the project I'm currently working on, I introduced an event listener to the component.

For window events I totally understand the perspective, but for component related event, in my mind it does not make a lot of sense, because why should I remove an event listener from a component that no longer exists in the DOM?

useEffect(() => {
  function cancelAutoPlay() {
    setIsAutoScrollOn(false)
  }

  carouselContainerRef.current.addEventListener('touchstart', cancelAutoPlay)
  return () => {
    if (carouselContainerRef?.current) {
      carouselContainerRef.current.removeEventListener('touchstart', cancelAutoPlay)
    }
  }
}, [])

Is this the right way? There is another way for doing it? Should I not care about removing it?

Victor Thadeu
  • 89
  • 1
  • 7
  • First of all, using `carouselContainerRef.current` on unmount doesn't guarantee it holds a value, you even get a LINT warning for that! So actually `carouselContainerRef?.current` should be considered nullable, so this code block is useless. – Dennis Vash May 10 '21 at 12:33
  • But, the question is to which element the ref is attached too, it can be attached to an element outside the DOM which Reacts handles, therefore you DO need to removeListener for it, just do it right: copy the ref into the scope and don't use `.current` as mentioned before. – Dennis Vash May 10 '21 at 12:34
  • So to fully answer this question... We need reproducible example as always (attaching a codesandbox). [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) – Dennis Vash May 10 '21 at 12:35

0 Answers0