useWindowScrollPosition
Returns reactive horizontal and vertical window scroll coordinates.
About
useWindowScrollPosition reads the current window scroll coordinates and refreshes them after window scroll and resize events.
Example
import { useWindowScrollPosition } from "rooks";
export default function ScrollPosition() {
const { scrollX, scrollY } = useWindowScrollPosition();
return (
<p>
Window scroll position: {scrollX}px horizontally, {scrollY}px vertically
</p>
);
}Parameters
This hook has no parameters.
Return value
It returns { scrollX: number, scrollY: number }. Each field uses the corresponding modern window property and falls back to pageXOffset or pageYOffset.
Behavior and lifecycle
Initial state is read during render. Scroll and resize callbacks recompute both coordinates; their listeners are passive and synchronized during the layout-effect phase. The hook does not throttle updates. Both subscriptions are removed on unmount.
Compatibility and accessibility
During server rendering both coordinates are 0. A client rendering at a nonzero scroll position can therefore differ from server output; avoid using the first coordinates for hydration-sensitive markup or layout. Scroll position is visual context, so do not use it to remove the only keyboard-accessible route to content.
Related
- useOnWindowScroll runs a callback without storing coordinates.
- useWindowSize returns inner and outer window dimensions.
- SSR and browser APIs covers hydration-safe fallbacks.