useScrollPositionui-interaction
useScrollPosition
NewSSR SAFETracks scroll coordinates and direction in real time for the window or a specific scrollable element.
$ pnpm dlx shadcn@latest add @byphongphan/use-scroll-positionRequires
@byphongphan in components.jsonuse-scroll-position.tsx
Loading preview...
Installation
$ pnpm dlx shadcn@latest add @byphongphan/use-scroll-positionRequires
@byphongphan in components.jsonUsage
Window Scroll (e.g. Auto-Hiding Navbar)
Custom Scrollable Container
Features
- 60/120 FPS Performance: Throttled using native
requestAnimationFrameto ensure zero main-thread blockage or frame drops during heavy scrolling. - Direction Detection: Automatically identifies
"up"vs"down"movement to power floating action buttons, auto-hiding navigation bars, and reading progress bars. - Target Agnostic: Listens to the global
windowby default or any scrollable HTML element viatargetRef. - Passive Listeners: Employs
{ passive: true }event listeners so mobile touch-scrolling remains butter-smooth. - SSR-Safe: Safely initializes on the server and synchronizes state on client mount with
useIsomorphicLayoutEffect.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
options.targetRef | RefObject<HTMLElement | null> | — | Optional ref of a scrollable element to observe instead of window. |
options.enabled | boolean | true | Pass false to pause event listeners and reduce overhead. |
Returns
| Property | Type | Description |
|---|---|---|
x | number | Horizontal scroll offset in pixels (scrollLeft). |
y | number | Vertical scroll offset in pixels (scrollTop). |
direction | "up" | "down" | null | Active scroll direction since previous frame ("up", "down" or null). |