CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/next/lib/use-scroll-y.tsx
Views: 687
1
/*
2
* This file is part of CoCalc: Copyright © 2022 Sagemath, Inc.
3
* License: MS-RSL – see LICENSE.md for details
4
*/
5
6
import { throttle } from "lodash";
7
import { useCallback, useEffect, useState } from "react";
8
9
// dynamically get the Y position of the window scroll
10
export function useScrollY() {
11
const [scrollY, setScrollY] = useState(0);
12
13
// callback is important, since we want to reain the same reference
14
const onScroll = useCallback(
15
throttle(
16
(_event) => {
17
setScrollY(window.pageYOffset);
18
},
19
100,
20
{ trailing: true }
21
),
22
[]
23
);
24
25
useEffect(() => {
26
// passive: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#improving_scrolling_performance_with_passive_listeners
27
window.addEventListener("scroll", onScroll, { passive: true });
28
return () => window.removeEventListener("scroll", onScroll);
29
}, []);
30
31
return scrollY;
32
}
33
34