Installation
Props
| Prop | Type | Default | Description |
|---|---|---|---|
onChange? | (x: number, y: number) => void | undefined | A callback function called when the scroll position changes. |
Data
| Prop | Type | Description |
|---|---|---|
x | number | The horizontal scroll offset (px). |
y | number | The vertical scroll offset (px). |
Key Features & Details
SSR & Initial Values
- The hook checks if it's running in a browser. On the server, it returns
0for bothxandy. - On mount, the hook initializes the scroll position based on the current
window.scrollXandwindow.scrollY.
Passive Scroll Listener
- The scroll listener is registered with
{ passive: true }for better performance. - The listener is cleaned up on unmount to prevent memory leaks.
Examples
Basic Usage
const { x, y } = useScrollPosition();
return (
<div>
Scroll position: {x} x {y}
</div>
);With onChange Callback
useScrollPosition({
onChange: (x, y) => {
console.log('Scroll position:', x, y);
},
});