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?
You should always pass handleScroll in the useEffects deps array.
Then, ways to limit re-rendering include wrapping handleScroll inside a useCallback and using refs.
Based on your limited example, not knowing for sure, but the ref approach in the useEventCallback example from the react docs might be helpful for your situation.
import { useEventCallback } from './myHooks'
function Component() {
const [myChangingState, changeIt] = useState()
const handleScroll = useEventCallback(() => {
// body uses `myChangingState`
}, [myChangingState]
)
which will keep it from updating on every render.