-
Notifications
You must be signed in to change notification settings - Fork 12
/
index.js
62 lines (51 loc) · 1.42 KB
/
index.js
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
// @flow
import { useRef, useState, useEffect } from 'react';
import areInputsEqual from './are-inputs-equal';
type Cache<T> = {|
inputs: ?(mixed[]),
result: T,
|};
export function useMemoOne<T>(
// getResult changes on every call,
getResult: () => T,
// the inputs array changes on every call
inputs?: mixed[],
): T {
// using useState to generate initial value as it is lazy
const initial: Cache<T> = useState(() => ({
inputs,
result: getResult(),
}))[0];
const committed = useRef<Cache<T>>(initial);
// persist any uncommitted changes after they have been committed
const isInputMatch: boolean = Boolean(
inputs &&
committed.current.inputs &&
areInputsEqual(inputs, committed.current.inputs),
);
// create a new cache if required
const cache: Cache<T> = isInputMatch
? committed.current
: {
inputs,
result: getResult(),
};
// commit the cache
useEffect(() => {
committed.current = cache;
}, [cache]);
return cache.result;
}
export function useCallbackOne<T: Function>(
// getResult changes on every call,
callback: T,
// the inputs array changes on every call
inputs?: mixed[],
): T {
return useMemoOne(() => callback, inputs);
}
// Aliased exports
// A drop in replacement for useMemo and useCallback that plays
// very well with eslint-plugin-react-hooks
export const useMemo = useMemoOne;
export const useCallback = useCallbackOne;