blob: 0e805966ae7be70be177632dc5843737c243a24a (
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
44
45
46
|
import { useRef, useEffect } from 'react';
export const usePrevious = (value) => {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
};
export const useEffectAsync = (effect, deps) => {
const ref = useRef();
useEffect(() => {
effect().then((result) => ref.current = result);
return () => {
const result = ref.current;
if (result) {
result();
}
};
}, deps);
};
// Source: https://overreacted.io/making-setinterval-declarative-with-react-hooks/
export const useInterval = (callback, delay) => {
const ref = useRef();
let id = null;
// Remember the latest callback.
useEffect(() => {
ref.current = callback;
}, [callback]);
// Set up the interval.
useEffect(() => {
function tick() {
ref.current();
}
if (delay !== null) {
id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]);
return id;
}
|