Skip to main content
Version: 5.x

useScroll

The useScroll hook captures scroll activity on any DOM element or the window. It reports how far you scrolled, how fast, and gives access to the native scroll event.

Syntax

useScroll(
refs: RefObject<HTMLElement> | RefObject<HTMLElement>[] | window,
callback: (event: ScrollEvent & { index: number }) => void
): void

Parameters

NameTypeDescription
Refs (required)RefObject<HTMLElement> or RefObject<HTMLElement>[] or WindowThe scrollable target(s). You can pass a single ref, a list, or window.
Callback (required)(event:ScrollEvent) => voidGets called on scroll change and scroll end. index maps to ref position.

ScrollEvent Signature

type ScrollEvent = {
index: number
movement: { x: number; y: number }; // Change since last scroll frame
offset: { x: number; y: number }; // Current scroll position
velocity: { x: number; y: number }; // Pixels/ms
event: Event; // Native scroll event
cancel?: () => void; // Optional cancel gesture cleanup
};

Example: Track Scroll Position Using useScroll

This example demonstrates how to use the useScroll hook to track the scroll position of the window in real-time.

import React, { useState } from 'react';
import { useScroll } from 'react-ui-animate';

const App = () => {
  const [scrollPosition, setScrollPosition] = useState(0);

  useScroll(window, function (event) {
    setScrollPosition(event.offset.y);
  });

  return (
    <div style={{ height: 2000 }}>
      <div style={{ position: 'fixed', left: 10, top: 10 }}>
        SCROLL POSITION: {scrollPosition}
      </div>
    </div>
  );
};

export default App;