useScrollPosition Hook
A custom React Hook to track scroll position of window/element with TypeScript support
Code
import { useState, useEffect, RefObject } from 'react';
type ScrollPosition = {
x: number;
y: number;
};
function useScrollPosition<T extends HTMLElement = HTMLElement>(
elementRef?: RefObject<T>
): ScrollPosition {
const [scrollPosition, setScrollPosition] = useState<ScrollPosition>({
x: 0,
y: 0,
});
useEffect(() => {
const target = elementRef?.current || window;
__TOKEN_18__ (!target) return;
const handleScroll = () => {
setScrollPosition({
x: target === window ? window.scrollX : target.scrollLeft,
y: target === window ? window.scrollY : target.scrollTop,
});
};
target.addEventListener('scroll', handleScroll, { passive: true });
handleScroll(); // Initial position
__TOKEN_21__ () => {
target.removeEventListener('scroll', handleScroll);
};
}, [elementRef]);
return scrollPosition;
}
// Usage example
// // Track window scroll
// const { y: scrollY } = useScrollPosition();
// const isScrolled = scrollY > 100;
// // Track element scroll
// const containerRef = useRef<HTMLDivElement>(null);
// const { y: containerScrollY } = useScrollPosition(containerRef);