Skip to Content
ohooks

useWindowScroll

Tracks the window scroll position (x, y) and provides a scrollTo helper.

Loading preview...

The useWindowScroll hook tracks window.scrollX and window.scrollY with passive event listeners (optional throttleMs), and provides a programmatic scrollTo helper.

Installation

pnpm dlx shadcn@latest add https://ohooks.vercel.app/r/useWindowScroll.json

Usage

Examples

Floating "Back to Top" Button

Show a button once the user scrolls past 300px vertically and smoothly scroll back to the top on click.

Throttling Scroll Updates

Set throttleMs to reduce the frequency of state updates during fast scrolling.

API Reference

UseWindowScrollOptions

Configuration options for scroll throttling and SSR fallback coordinates.

Property
Specification
initializeWithValue?
uniondefault:true
Read window.scrollX/scrollY synchronously on initial client render
throttleMs?
numberdefault:0
Optional throttle interval in milliseconds for scroll updates

WindowScrollPosition

Horizontal (x) and vertical (y) scroll coordinates.

Property
Specification
xrequired
number
Horizontal scroll offset (window.scrollX).
yrequired
number
Vertical scroll offset (window.scrollY).

UseWindowScrollReturn

Scroll coordinates and scrollTo helper returned by the hook.

Property
Specification
scrollTo
function
Scrolls the window to the given coordinates or ScrollToOptions.
x
number
Horizontal scroll offset (window.scrollX).
y
number
Vertical scroll offset (window.scrollY).