useScroll

A React hook that tracks scroll position, direction, and progress with high precision.

Overview

useScroll provides comprehensive data about the user's scroll activity. It tracks exact coordinates, scroll direction (up/down), and normalized progress (0-1), enabling you to build adaptive interfaces like smart navbars and reading progress indicators.

Demo

Adaptive Interface

Tracking the internal container scroll state below.

Integrated Playground
CW
React Hooks TS
0%
Offset Y0px
Direction
Idle

API Reference

function useScroll(ref?: React.RefObject<HTMLElement>): {
  x: number,
  y: number,
  progress: number,
  direction: 'up' | 'down' | null
}

Parameters

NameTypeDescription
refReact.RefObject<HTMLElement>Optional. A React ref to a scrollable element. If omitted, the hook tracks the global window scroll.

Returns

NameTypeDescription
xnumberCurrent horizontal scroll position in pixels.
ynumberCurrent vertical scroll position in pixels.
progressnumberNormalized scroll progress (from 0 to 1).
direction'up' | 'down' | nullThe last detected scroll direction.

Usage Examples

Smart Reading Progress

import { useScroll } from 'react-hooks-ts'
 
function ReadingProgress() {
  const { progress } = useScroll()
 
  return (
    <div 
      className="fixed top-0 left-0 h-1 bg-blue-500 transition-all duration-150"
      style={{ width: `${progress * 100}%` }}
    />
  )
}

Features

  • Optimized - Uses passive event listeners for high performance.
  • 🎯 Direction Aware - Easily detect whether the user is moving forward or returning.
  • 🧩 Normalized Progress - Get a clean 0-1 value for progress-based animations.
  • 🛡️ SSR Safe - Works gracefully with Next.js server-side rendering.