1 | import { useRef } from 'react';
|
2 |
|
3 | function isEqual(a, b) {
|
4 | if (a.length !== b.length) return false;
|
5 |
|
6 | for (var i = 0; i < a.length; i++) {
|
7 | if (a[i] !== b[i]) {
|
8 | return false;
|
9 | }
|
10 | }
|
11 |
|
12 | return true;
|
13 | }
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 | export default function useStableMemo(factory, deps) {
|
24 | var isValid = true;
|
25 | var valueRef = useRef();
|
26 |
|
27 | if (!valueRef.current) {
|
28 | valueRef.current = {
|
29 | deps: deps,
|
30 | result: factory()
|
31 | };
|
32 | } else {
|
33 | isValid = !!(deps && valueRef.current.deps && isEqual(deps, valueRef.current.deps));
|
34 | }
|
35 |
|
36 | var cache = isValid ? valueRef.current : {
|
37 | deps: deps,
|
38 | result: factory()
|
39 | };
|
40 |
|
41 | valueRef.current = cache;
|
42 | return cache.result;
|
43 | } |
\ | No newline at end of file |