HooksuseScrollPosition

useScrollPosition()

The useScrollPosition() hook tracks the global window scroll coordinates in real-time. It is useful for creating reading progress bars, sticky navigation menus, or triggering animations as the user scrolls down the page.

Import

typescript
import { useScrollPosition } from 'the-react-hooks';

Usage

Scroll the page up and down to see the values update.

Window Scroll Coordinates
0X-Axis (px)
0Y-Axis (px)
Page Progress: 0%
Component.tsx
import { useScrollPosition } from 'the-react-hooks';

export const Component = () => {
  const { y } = useScrollPosition();

  const isScrolled = y > 50;

  return (
    <nav style={{ 
      position: 'fixed', 
      top: 0, 
      opacity: isScrolled ? 1 : 0.8,
      boxShadow: isScrolled ? '0 2px 4px rgba(0,0,0,0.1)' : 'none' 
    }}>
      My Sticky Navbar (Scroll Y: {y}px)
    </nav>
  );
}

API

Arguments

This hook does not accept any arguments.

Returns

Returns an object containing the scroll coordinates:
  • x number The horizontal scroll amount in pixels (from window.pageXOffset).
  • y number The vertical scroll amount in pixels (from window.pageYOffset).