Rooks
HooksEvent Handling

useOnWindowScroll

Calls a callback for passive window scroll events.

About

useOnWindowScroll runs a callback when the window scrolls. It is an event hook; use useWindowScrollPosition when render output needs the current coordinates.

Example

import { useState } from "react";
import { useOnWindowScroll } from "rooks";

export default function ScrollReporter() {
  const [lastY, setLastY] = useState(0);

  useOnWindowScroll(() => {
    setLastY(window.scrollY);
  });

  return <p>Last reported vertical scroll: {lastY}px</p>;
}

Parameters

  • callback(event): receives the native scroll Event.
  • when: enables the listener; defaults to true.
  • isLayoutEffect: subscribes during the layout-effect phase when true; defaults to false.

Return value

The hook returns void.

Behavior and lifecycle

The hook attaches a passive scroll listener to window. Changing when to false detaches it. It keeps the callback fresh, replaces the subscription when its configuration changes, and removes the listener on unmount.

Compatibility and accessibility

There is no window subscription during server rendering. Scroll events can be frequent and the hook does not throttle callbacks. Avoid scroll-driven motion that ignores reduced-motion preferences, and do not hide focusable content only because it moved outside a visual threshold.

On this page