useContainerScroll
A React hook that tracks scroll position of a container element in real-time, providing both vertical and horizontal scroll coordinates. Perfect for implementing scroll-based animations, custom scrollbars, or scroll progress indicators within specific containers.
Interactive Demo
Scroll Position: X: 0px, Y: 0px
Try scrolling this container both horizontally and vertically to see the scroll position update in real-time.
Implementation
interface ScrollPosition {
x: number;
y: number;
}
export function useContainerScroll(ref: RefObject<HTMLElement | null>): ScrollPosition {
const [scrollPosition, setScrollPosition] = useState<ScrollPosition>({ x: 0, y: 0 });
useEffect(() => {
const element = ref.current;
if (!element) return;
const handleScroll = () => {
setScrollPosition({
x: element.scrollLeft,
y: element.scrollTop,
});
};
element.addEventListener("scroll", handleScroll, { passive: true });
handleScroll(); // Initial position
return () => {
element.removeEventListener("scroll", handleScroll);
};
}, [ref]);
return scrollPosition;
}
Usage Examples
import { useRef } from 'react';
import { useContainerScroll } from '@/components/hooks/useContainerScroll';
function ScrollableContainer() {
const containerRef = useRef<HTMLDivElement>(null);
const { x, y } = useContainerScroll(containerRef);
return (
<div>
<div>Scroll X: {x}px, Y: {y}px</div>
<div
ref={containerRef}
className="w-full h-[400px] overflow-auto"
>
{/* Scrollable content */}
</div>
</div>
);
}
Documentation
Key Features
- Real-time scroll position tracking for any container element
- Tracks both horizontal (x) and vertical (y) scroll positions
- TypeScript support with proper typing
- Automatic cleanup of scroll listeners
- Memory efficient with passive event listeners
- SSR compatible
Common Use Cases
- Custom scrollbars
- Scroll-based animations within containers
- Infinite scrolling in specific elements
- Scroll progress indicators
- Scroll-based content loading
API Reference
useContainerScroll(ref: RefObject<HTMLElement>): ScrollPosition
Returns the current scroll position of the container element.
Parameters:
- ref: React ref object pointing to the container element
Returns:
- ScrollPosition: Object containing x and y coordinates
Browser Compatibility
The hook uses standard scroll event listeners and element properties (scrollLeft, scrollTop) which are supported in all modern browsers. For optimal performance, the hook uses passive event listeners where available.