MCPcopy Create free account
hub / github.com/streamich/react-use / useWindowScroll

Function useWindowScroll

src/useWindowScroll.ts:11–47  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

9}
10
11const useWindowScroll = (): State => {
12 const [state, setState] = useRafState<State>(() => ({
13 x: isBrowser ? window.pageXOffset : 0,
14 y: isBrowser ? window.pageYOffset : 0,
15 }));
16
17 useEffect(() => {
18 const handler = () => {
19 setState((state) => {
20 const { pageXOffset, pageYOffset } = window;
21 //Check state for change, return same state if no change happened to prevent rerender
22 //(see useState/setState documentation). useState/setState is used internally in useRafState/setState.
23 return state.x !== pageXOffset || state.y !== pageYOffset
24 ? {
25 x: pageXOffset,
26 y: pageYOffset,
27 }
28 : state;
29 });
30 };
31
32 //We have to update window scroll at mount, before subscription.
33 //Window scroll may be changed between render and effect handler.
34 handler();
35
36 on(window, 'scroll', handler, {
37 capture: false,
38 passive: true,
39 });
40
41 return () => {
42 off(window, 'scroll', handler);
43 };
44 }, []);
45
46 return state;
47};
48
49export default useWindowScroll;

Callers 3

DemoFunction · 0.90
getHookFunction · 0.85
TestComponentFunction · 0.85

Calls 4

onFunction · 0.90
offFunction · 0.90
useRafStateFunction · 0.85
handlerFunction · 0.70

Tested by 2

getHookFunction · 0.68
TestComponentFunction · 0.68

Used in the wild real call sites across dependent graphs

searching dependent graphs…