-
Notifications
You must be signed in to change notification settings - Fork 96
/
Copy pathindex.ts
59 lines (48 loc) · 1.3 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import {useCallback, useMemo, useRef} from 'react';
import {useSyncedRef} from '../useSyncedRef/index.js';
import {useUnmountEffect} from '../useUnmountEffect/index.js';
import {isBrowser} from '../util/const.js';
/**
* Makes passed function to be called within next animation frame.
*
* Consequential calls, before the animation frame occurred, cancel previously scheduled call.
*
* @param cb Callback to fire within animation frame.
*/
export function useRafCallback<T extends (...args: any[]) => any>(
cb: T,
): [(...args: Parameters<T>) => void, () => void] {
const cbRef = useSyncedRef(cb);
const frame = useRef<number>(0);
const cancel = useCallback(() => {
if (!isBrowser) {
return;
}
if (frame.current) {
cancelAnimationFrame(frame.current);
frame.current = 0;
}
}, []);
useUnmountEffect(cancel);
return [
useMemo(() => {
const wrapped = (...args: Parameters<T>) => {
if (!isBrowser) {
return;
}
cancel();
frame.current = requestAnimationFrame(() => {
cbRef.current(...args);
frame.current = 0;
});
};
Object.defineProperties(wrapped, {
length: {value: cb.length},
name: {value: `${cb.name || 'anonymous'}__raf`},
});
return wrapped;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []),
cancel,
];
}