useWindowScroll
useWindowScroll is a React Hook that is used to get the scroll position of the browser window
useWindowScroll returns the current horizontal (x) and vertical (y) scroll position of the browser window as a reactive state object. It listens to the scroll event on the window and updates the values whenever the user scrolls. This provides a simple way to access window.scrollX and window.scrollY as React state.
When to Use
- Building scroll-progress indicators or reading-position trackers
- Implementing parallax scrolling effects or scroll-linked animations
- Showing or hiding UI elements (e.g., “back to top” buttons) based on the current scroll position
Notes
- SSR-safe: Returns
{ x: 0, y: 0 }during server-side rendering sincewindowis not available. - Performance: The hook listens to the window
scrollevent. For high-frequency scroll tracking, consider combining withrequestAnimationFrameor throttling in your consuming component. - See also
useStickyfor detecting when an element should become sticky, anduseWindowSizefor tracking viewport dimensions.
Usage
Live Editor
function Demo() { return ( <div> <div> <iframe src="https://codesandbox.io/embed/dreamy-lehmann-mzg96r?fontsize=14&hidenavigation=1&theme=dark" style={{ width: "100%", height: 500, border: 0, borderRadius: 4, overflow: "hidden", }} title="dreamy-lehmann-mzg96r" allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts" > </iframe> </div> </div> ); };
Result
API
useWindowScroll
Returns
UseWindowScrollState
Arguments
useWindowScrollState
| Property | Description | Type | DefaultValue |
|---|---|---|---|
| x | pixel value of horizontal scrolling | number (Required) | - |
| y | pixel value of vertical scrolling | number (Required) | - |