-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.ts
45 lines (36 loc) · 1.11 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import { useState, useEffect } from 'react';
interface ScrollPosition {
x: number;
y: number;
}
const isBrowser = typeof window !== `undefined`;
function getScrollPosition(): ScrollPosition {
return isBrowser ? { x: window.pageXOffset, y: window.pageYOffset } : { x: 0, y: 0 };
}
export function useScrollPosition(): ScrollPosition {
const [position, setScrollPosition] = useState<ScrollPosition>(getScrollPosition());
useEffect(() => {
let requestRunning: number | null = null;
function handleScroll() {
if (isBrowser && requestRunning === null) {
requestRunning = window.requestAnimationFrame(() => {
setScrollPosition(getScrollPosition());
requestRunning = null;
});
}
}
if (isBrowser) {
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
}
}, []);
return position;
}
export function useScrollXPosition(): number {
const { x } = useScrollPosition();
return x;
}
export function useScrollYPosition(): number {
const { y } = useScrollPosition();
return y;
}