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 scrollEvent.when: enables the listener; defaults totrue.isLayoutEffect: subscribes during the layout-effect phase whentrue; defaults tofalse.
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.
Related
- useWindowScrollPosition returns reactive scroll coordinates.
- useWindowEventListener handles arbitrary window events.