Skip to content

useScrollPosition()

useScrollPosition(element?, percentage?, debounce?, initialValue?): number

Defined in: src/hooks/dom/useScrollPosition.ts:48

A custom React hook to track the vertical scroll position of a specific element or the window. Automatically updates whenever the user scrolls.

Parameters

element?

The target element to track. Defaults to globalThis which is window (global scroll position).

typeof globalThis | HTMLElement

percentage?

boolean = false

Whether to return the scroll position as a percentage. Defaults to false.

debounce?

number = 0

The debounce delay in milliseconds for the scroll event. Defaults to 0 (no debounce).

initialValue?

number = 0

The initial scroll position value.

Returns

number

The current vertical scroll position.

Examples

Example: Tracking the scroll position of the page

tsx
import { useScrollPosition } from '@zl-asica/react';

const MyComponent = () => {
  const scrollPosition = useScrollPosition();

  return <div>Scroll Position: {scrollPosition}</div>;
};

Example: Tracking the scroll position of a specific container

tsx
import { useRef } from 'react';
import { useScrollPosition } from '@zl-asica/react';

const MyComponent = () => {
  const containerRef = useRef<HTMLDivElement | null>(null);
  const scrollPosition = useScrollPosition(containerRef.current);

  return (
    <div ref={containerRef} style={{ height: '200px', overflowY: 'scroll' }}>
      <div style={{ height: '500px' }}>Content</div>
      <div>Scroll Position: {scrollPosition}</div>
    </div>
  );
};

Released under the MIT License.