MCPcopy Create free account
hub / github.com/bvaughn/react-window / useIsScrolling

Function useIsScrolling

lib/hooks/useIsScrolling.ts:20–93  ·  view source on GitHub ↗
(
  target: "window" | HTMLElement | null | undefined,
  {
    delay = 150
  }: {
    /**
     * Milliseconds without scroll events after which scrolling is considered to have ended
     * (only used by browsers that don't support the "scrollend" event); defaults to 150.
     */
    delay?: number;
  } = {}
)

Source from the content-addressed store, hash-verified

18 * ⚠️ Changing this value re-renders any rows it is passed to (e.g. via `rowProps`) when scrolling starts and when it ends.
19 */
20export function useIsScrolling(
21 target: "window" | HTMLElement | null | undefined,
22 {
23 delay = 150
24 }: {
25 /**
26 * Milliseconds without scroll events after which scrolling is considered to have ended
27 * (only used by browsers that don't support the "scrollend" event); defaults to 150.
28 */
29 delay?: number;
30 } = {}
31): boolean {
32 const [isScrolling, setIsScrolling] = useState(false);
33
34 useIsomorphicLayoutEffect(() => {
35 if (!target) {
36 return;
37 }
38
39 const ownerWindow =
40 target === "window" ? window : getOwnerWindow(target as HTMLElement);
41 const eventTarget = target === "window" ? ownerWindow : target;
42
43 // Checked against a plain object, since TypeScript assumes all windows support the event
44 const supportsScrollEnd = "onscrollend" in (ownerWindow as object);
45
46 let animationFrameId: number | undefined = undefined;
47 let lastScrollTime = 0;
48
49 // Timeouts can be starved while scrolling (see issue #106), so check the elapsed time each frame instead
50 const checkForScrollEnd = () => {
51 if (performance.now() - lastScrollTime >= delay) {
52 animationFrameId = undefined;
53 setIsScrolling(false);
54 } else {
55 animationFrameId = ownerWindow.requestAnimationFrame(checkForScrollEnd);
56 }
57 };
58
59 const onScroll = () => {
60 setIsScrolling(true);
61
62 if (!supportsScrollEnd) {
63 lastScrollTime = performance.now();
64 if (animationFrameId === undefined) {
65 animationFrameId =
66 ownerWindow.requestAnimationFrame(checkForScrollEnd);
67 }
68 }
69 };
70
71 const onScrollEnd = () => {
72 setIsScrolling(false);
73 };
74
75 eventTarget.addEventListener("scroll", onScroll, { passive: true });
76 if (supportsScrollEnd) {
77 eventTarget.addEventListener("scrollend", onScrollEnd);

Callers 4

ExampleFunction · 0.85
ExampleFunction · 0.85
ListScrollElementRouteFunction · 0.85

Calls 1

getOwnerWindowFunction · 0.90

Tested by

no test coverage detected