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?