Files
admin/packages/hooks/src/useScrollPosition/Readme.md
T
2026-06-25 15:53:49 +03:00

1.4 KiB

useScrollPosition

Tracks the vertical scroll position of the window or a specific scrollable element.

Signature

function useScrollPosition(options?: { targetRef?: RefObject<HTMLElement | Document> }): number;

Options

Option Type Default Description
targetRef RefObject<HTMLElement | Document> document Ref to a scrollable element; falls back to the document

Returns the current scrollY (window) or scrollTop (element) as a number.

Usage

// Track window scroll
function ScrollProgress() {
  const scrollY = useScrollPosition();

  return <div>Scrolled: {scrollY}px</div>;
}
// Track a specific scrollable container
function VirtualList() {
  const containerRef = useRef<HTMLDivElement>(null);
  const scrollTop = useScrollPosition({ targetRef: containerRef });

  return (
    <div ref={containerRef} style={{ overflowY: 'auto', height: 400 }}>
      {/* items */}
    </div>
  );
}

Notes

  • Initial position is read synchronously on mount so there is no flash to 0.
  • Automatically switches between window.scrollY and element.scrollTop based on the target.
  • Client-only ('use client').