JAVASCRIPT

Track Window Scroll Position with useScrollPosition Hook

A versatile React hook to efficiently track the scroll position of the window, enabling dynamic UI elements based on scrolling.

import { useState, useEffect, useCallback } from 'react';

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

  const handleScroll = useCallback(() => {
    setScrollPosition({ x: window.scrollX, y: window.scrollY });
  }, []);

  useEffect(() => {
    window.addEventListener('scroll', handleScroll);
    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, [handleScroll]);

  return scrollPosition;
}
How it works: The `useScrollPosition` hook provides an easy way to monitor the horizontal and vertical scroll position of the browser window. It uses `useState` to store the current position and `useEffect` to attach and clean up a scroll event listener, ensuring that the scroll position is always up-to-date and preventing memory leaks.

Need help integrating this into your project?

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

Hire DigitalCodeLabs