JAVASCRIPT
React `useScrollPosition` Hook to Track Scroll Position
A reusable React hook that monitors and provides the current vertical and horizontal scroll position of the window or a specified DOM element in real-time, useful for animations.
import { useState, useEffect, useRef } from 'react';
const isBrowser = typeof window !== 'undefined';
function useScrollPosition(elementRef = null) {
const [scrollPosition, setScrollPosition] = useState({
x: isBrowser ? window.scrollX : 0,
y: isBrowser ? window.scrollY : 0,
});
const ticking = useRef(false);
useEffect(() => {
if (!isBrowser) return;
const handleScroll = () => {
if (!ticking.current) {
window.requestAnimationFrame(() => {
const target = elementRef?.current || window;
setScrollPosition({
x: target === window ? window.scrollX : target.scrollLeft,
y: target === window ? window.scrollY : target.scrollTop,
});
ticking.current = false;
});
ticking.current = true;
}
};
const targetElement = elementRef?.current || window;
targetElement.addEventListener('scroll', handleScroll);
return () => {
targetElement.removeEventListener('scroll', handleScroll);
};
}, [elementRef]);
return scrollPosition;
}
export default useScrollPosition;
How it works: The `useScrollPosition` hook provides real-time updates of the scroll position, either for the entire window or a specific DOM element via a `ref`. It uses `requestAnimationFrame` to debounce scroll events, optimizing performance by preventing excessive re-renders. This hook is ideal for implementing scroll-based animations, sticky headers, lazy loading content based on scroll depth, or other scroll-aware UI components.