useScrollPosition
A React hook that tracks window scroll position in real-time, providing both vertical and horizontal scroll coordinates. Perfect for implementing scroll-based animations, infinite scrolling, or scroll progress indicators.
Interactive Demo
Scroll Position X: 0px
Scroll Position Y: 0px
Implementation
export function useScrollPosition() {
const [scrollPosition, setScrollPosition] = useState({
x: typeof window !== "undefined" ? window.scrollX : 0,
y: typeof window !== "undefined" ? window.scrollY : 0,
});
useEffect(() => {
const handleScroll = () => {
setScrollPosition({
x: window.scrollX,
y: window.scrollY,
});
};
window.addEventListener("scroll", handleScroll, { passive: true });
return () => {
window.removeEventListener("scroll", handleScroll);
};
}, []);
return scrollPosition;
}
Usage Examples
import { useScrollPosition } from '@/components/hooks/useScrollPosition';
function ScrollTracker() {
const { x, y } = useScrollPosition();
return (
<div className="fixed bottom-4 right-4 p-4 bg-white shadow rounded">
<div>Scroll X: {Math.round(x)}px</div>
<div>Scroll Y: {Math.round(y)}px</div>
</div>
);
}
Documentation
Key Features
- Real-time scroll position tracking
- Support for both horizontal and vertical scroll
- TypeScript support with proper typing
- Optimized performance with passive event listeners
- Automatic cleanup of event listeners
- SSR compatible
Common Use Cases
- Scroll-based animations
- Infinite scrolling implementations
- Scroll progress indicators
- Scroll-to-top buttons
- Scroll-based navigation highlights
API Reference
useScrollPosition(): { x: number, y: number }
Returns an object containing the current scroll position coordinates.