guarahooks's logo

guarahooks

Command Palette

Search for a command to run...

useScrollPosition

Tracks the current scroll position of the page.

useScrollPosition
This component uses the useScrollPosition hook to track the page scroll position.

Scroll X: 0px

Scroll Y: 0px

Scroll the page to see the values change.

Installation

Props

PropTypeDefaultDescription
onChange?(x: number, y: number) => voidundefinedA callback function called when the scroll position changes.

Data

PropTypeDescription
xnumberThe horizontal scroll offset (px).
ynumberThe 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 0 for both x and y.
  • On mount, the hook initializes the scroll position based on the current window.scrollX and window.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);
  },
});