Skip to content
usefy

useScrollPosition

Layout & observers

Track the throttled scroll offset (x, y) of the window or a given element

Install

$ npm install @usefy/use-scroll-position

Quick start

useScrollPosition.tsx
import { useScrollPosition } from "@usefy/use-scroll-position";

function ScrollIndicator() {
  const { x, y } = useScrollPosition();

  return <div>Scrolled to {x}, {y}</div>;
}

API reference

useScrollPosition(options?)

Returns the current scroll offset of the tracked target, re-rendering (throttled) as it scrolls.

Options — UseScrollPositionOptions

OptionTypeDefaultDescription
elementHTMLElement | RefObject<HTMLElement> | nullwindowThe element (or a ref to it) whose scroll to track. Omit / null tracks the window/document
throttleMsnumber100Throttle interval in ms (leading + trailing). 0 updates on every scroll event (no throttle)

Returns — UseScrollPositionReturn (ScrollPosition)

PropertyTypeDescription
xnumberHorizontal offset — window.scrollX or the element's scrollLeft
ynumberVertical offset — window.scrollY or the element's scrollTop

Also exported: the ZERO_SCROLL_POSITION sentinel and the ScrollPosition, ScrollPositionTarget, UseScrollPositionOptions, and UseScrollPositionReturn types.

Go deeper

This page is the quick reference. For every example, prop, and edge case, read the full README — or open Storybook to change props live.

More in layout & observers