JAVASCRIPT

React useScrollPosition Hook for Scroll Tracking

Master the React useScrollPosition hook to monitor scroll coordinates, empowering effects like sticky headers, progress bars, or scroll-to-top buttons.

import { useState, useEffect } from 'react';

function useScrollPosition(elementRef = null) {
  const [scrollPosition, setScrollPosition] = useState({ x: 0, y: 0 });

  useEffect(() => {
    const handleScroll = () => {
      const target = elementRef?.current || window;
      setScrollPosition({
        x: target === window ? window.scrollX : target.scrollLeft,
        y: target === window ? window.scrollY : target.scrollTop,
      });
    };

    const scrollTarget = elementRef?.current || window;
    scrollTarget.addEventListener('scroll', handleScroll, { passive: true });

    // Initial call to set current scroll position
    handleScroll();

    return () => {
      scrollTarget.removeEventListener('scroll', handleScroll);
    };
  }, [elementRef]); // Re-run effect if elementRef changes

  return scrollPosition;
}

// Example Usage:
// function ScrollTracker() {
//   const { y: scrollY } = useScrollPosition();
//   const myDivRef = useRef(null);
//   const { y: divScrollY } = useScrollPosition(myDivRef);

//   return (
//     <div style={{ height: '200vh' }}>
//       <p style={{ position: 'fixed', top: '10px', left: '10px' }}>Window Scroll Y: {scrollY}</p>
//       <div ref={myDivRef} style={{ height: '500px', width: '300px', overflowY: 'scroll', border: '1px solid blue', marginTop: '100px' }}>
//         <p style={{ height: '1000px', margin: 0, padding: '10px' }}>
//           Scroll this div down to see its independent scroll position.
//           Div Scroll Y: {divScrollY}
//         </p>
//       </div>
//       <p style={{ marginTop: '1000px' }}>Content below for window scrolling</p>
//     </div>
//   );
// }
How it works: The `useScrollPosition` hook provides the current X and Y scroll coordinates of either the browser window or a specific DOM element (if a `ref` is provided). It attaches a scroll event listener, updating the state with the latest scroll position. This hook is useful for implementing features like sticky headers, scroll-triggered animations, or dynamic "scroll to top" buttons.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs