UNPKG

1.21 kBJavaScriptView Raw
1"use strict";
2
3exports.__esModule = true;
4exports.default = useStableMemo;
5var _react = require("react");
6function isEqual(a, b) {
7 if (a.length !== b.length) return false;
8 for (let i = 0; i < a.length; i++) {
9 if (a[i] !== b[i]) {
10 return false;
11 }
12 }
13 return true;
14}
15/**
16 * Identical to `useMemo` _except_ that it provides a semantic guarantee that
17 * values will not be invalidated unless the dependencies change. This is unlike
18 * the built in `useMemo` which may discard memoized values for performance reasons.
19 *
20 * @param factory A function that returns a value to be memoized
21 * @param deps A dependency array
22 */
23function useStableMemo(factory, deps) {
24 let isValid = true;
25 const valueRef = (0, _react.useRef)();
26 // initial hook call
27 if (!valueRef.current) {
28 valueRef.current = {
29 deps,
30 result: factory()
31 };
32 // subsequent calls
33 } else {
34 isValid = !!(deps && valueRef.current.deps && isEqual(deps, valueRef.current.deps));
35 }
36 const cache = isValid ? valueRef.current : {
37 deps,
38 result: factory()
39 };
40 // must update immediately so any sync renders here don't cause an infinite loop
41 valueRef.current = cache;
42 return cache.result;
43}
\No newline at end of file