It's pretty easy to add event listeners in the functional component:
const Component = () => {
const handleScroll = () => {
// body
}
useEffect(() => {
window.addEventListener('scroll', handleScroll);
return () => {
window.removeEventListener('scroll', handleScroll);
}
}, [])
}
But it's okay if handleScroll doesn't change. Sometimes it changes a lot (due to props change, state changes and etc.) and it should be added to useEffect dependencies list:
useEffect(() => {
window.addEventListener('scroll', handleScroll);
return () => {
window.removeEventListener('scroll', handleScroll);
}
}, [handleScroll])
Is it a normal practice to add and remove window listeners on almost each render of the component? Maybe, it's the situation when it's better to use class components that have an internal state?