React useOnWindowScroll hook
Executes a callback whenever the window is scrolled.
- Use the
useRef()
hook to create a variable,listener
, which will hold the listener reference. - Use the
useEffect()
hook andEventTarget.addEventListener()
to listen to the'scroll'
event of theWindow
global object. - Use
EventTarget.removeEventListener()
to remove any existing listeners and clean up when the component unmounts.
const useOnWindowScroll = callback => {
const listener = React.useRef(null);
React.useEffect(() => {
if (listener.current)
window.removeEventListener('scroll', listener.current);
listener.current = window.addEventListener('scroll', callback);
return () => {
window.removeEventListener('scroll', listener.current);
};
}, [callback]);
};