Skip to main content

useScrollPosition

useScrollPosition is a custom hook to track scroll position, direction, and activity.

Usage

import { useScrollInfo } from "hookify-react";

export default function UseScrollPositionExample() {
const { ref, scrollX, scrollY, scrollDirection, isScrolling, scrollProgress } =
useScrollInfo<HTMLDivElement>();

return (
<div ref={ref} style={{ height: "300px", overflowY: "scroll", border: "1px solid black" }}>
<div style={{ height: "1000px", padding: "20px" }}>
<p>Scroll X: {scrollX}</p>
<p>Scroll Y: {scrollY}</p>
<p>Scroll Direction: {scrollDirection}</p>
<p>Is Scrolling: {isScrolling ? "Yes" : "No"}</p>
<p>Scroll Progress: {scrollProgress.toFixed(2)}%</p>
</div>
</div>
);
}

API Reference

Parameters

ParameterTypeDefaultDescription
None--This hook does not take any parameters. It tracks scroll information for either the window or a referenced element.

Return Value

PropertyTypeDescription
refReact.MutableRefObject<T | null>A ref that can be attached to an element to track its scrolling behavior. If not attached, the hook tracks the window.
scrollXnumberThe current horizontal scroll position.
scrollYnumberThe current vertical scroll position.
scrollDirection"up" | "down" | "left" | "right" | "none"The direction of the latest scroll movement.
isScrollingbooleanWhether the element is actively scrolling.
scrollProgressnumberThe percentage (0-100) of vertical scrolling completion.

Behavior

  • Tracks scroll position (scrollX, scrollY) and direction (scrollDirection).
  • Determines if the user is actively scrolling (isScrolling), resetting to false after a short idle period.
  • Calculates the vertical scroll progress percentage (scrollProgress, 0-100).
  • Tracks the element attached to ref, or the window when no ref is attached.
  • Uses a passive scroll listener (never blocks scrolling) and cleans up both the listener and its idle timer on unmount.