Executes a callback whenever the window is scrolled.
useRef()
hook to create a variable, listener
, which will hold the listener reference.useEffect()
hook and EventTarget.addEventListener()
to listen to the 'scroll'
event of the Window
global object.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]);
};
const App = () => {
useOnWindowScroll(() => console.log(`scroll Y: ${window.pageYOffset}`));
return <p style={{ height: '300vh' }}>Scroll and check the console</p>;
};
ReactDOM.render(<App />, document.getElementById('root'));
React, Hooks
Executes a callback whenever the window is resized.
React, Hooks
Executes a callback whenever an event occurs on the global object.
React, Hooks
Handles the beforeunload
window event.