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
API Reference
function useScroll(ref?: React.RefObject<HTMLElement>): {
x: number,
y: number,
progress: number,
direction: 'up' | 'down' | null
}Parameters
| Name | Type | Description |
|---|---|---|
ref | React.RefObject<HTMLElement> | Optional. A React ref to a scrollable element. If omitted, the hook tracks the global window scroll. |
Returns
| Name | Type | Description |
|---|---|---|
x | number | Current horizontal scroll position in pixels. |
y | number | Current vertical scroll position in pixels. |
progress | number | Normalized scroll progress (from 0 to 1). |
direction | 'up' | 'down' | null | The 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.