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
60
61
62
63
64
65
66
67
68
|
import { memo, useCallback, useEffect, useState } from "react";
export default function Parent() {
const [text, setText] = useState("");
const [count1, setCount1] = useState(0);
useEffect(() => {
const interval = setInterval(() => setCount1((prev) => prev + 1), 500);
return () => {
clearInterval(interval);
};
}, []);
const callback = useCallback(() => {
setText(`${count1}`);
}, [count1]);
const { call } = useThrottle(callback, 2000);
return (
<section>
<p>{count1}</p>
<p>{text}</p>
<ChildFunc func={call} />
</section>
);
}
type ChildProps = {
func: () => void;
};
const ChildFunc = memo<ChildProps>(function Child({ func }: ChildProps) {
useEffect(() => {
const interval1 = setInterval(() => {
func();
}, 100);
return () => {
clearInterval(interval1);
};
}, [func]);
return null;
});
function useThrottle(callback: () => void, wait: number) {
const [exec, setExec] = useState(true);
const [trigger, setTrigger] = useState(false);
useEffect(() => {
if (!exec) return;
callback();
setExec(false);
}, [exec, callback]);
useEffect(() => {
if (!trigger) return;
const timer = setTimeout(() => {
setExec(true);
setTrigger(false);
}, wait);
return () => clearTimeout(timer);
}, [trigger, wait]);
return {
call: useCallback(() => setTrigger(true), []),
};
}
|