Menu

gitpiper

useOnWindowScroll react Code Snippet in 2024

hookseffecteventintermediate

Last Updated: 17 December 2024

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 and EventTarget.addEventListener() to listen to the 'scroll' event of the window 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]); };
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 snippet similar to useOnWindowScroll For You in December 2024

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2024 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️