blob: 892e354529e36d907c47c71c9ffd210c4ab33009 (
plain)
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
|
import React from "react";
import { fromEvent } from "rxjs";
import { filter, throttleTime } from "rxjs/operators";
function useScrollToTop(
handler: () => void,
enable = true,
option = {
maxOffset: 50,
throttle: 1000,
}
): void {
const handlerRef = React.useRef<(() => void) | null>(null);
React.useEffect(() => {
handlerRef.current = handler;
return () => {
handlerRef.current = null;
};
}, [handler]);
React.useEffect(() => {
const subscription = fromEvent(window, "scroll")
.pipe(
filter(() => {
return window.scrollY <= option.maxOffset;
}),
throttleTime(option.throttle)
)
.subscribe(() => {
if (enable) {
handlerRef.current?.();
}
});
return () => {
subscription.unsubscribe();
};
}, [enable, option.maxOffset, option.throttle]);
}
export default useScrollToTop;
|