UNPKG

2.29 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', { value: true });
4
5var React = require('react');
6var dequal = require('dequal');
7
8function _interopNamespace(e) {
9 if (e && e.__esModule) return e;
10 var n = Object.create(null);
11 if (e) {
12 Object.keys(e).forEach(function (k) {
13 if (k !== 'default') {
14 var d = Object.getOwnPropertyDescriptor(e, k);
15 Object.defineProperty(n, k, d.get ? d : {
16 enumerable: true,
17 get: function () { return e[k]; }
18 });
19 }
20 });
21 }
22 n["default"] = e;
23 return Object.freeze(n);
24}
25
26var React__namespace = /*#__PURE__*/_interopNamespace(React);
27
28function checkDeps(deps) {
29 if (!deps || !deps.length) {
30 throw new Error('useDeepCompareEffect should not be used with no dependencies. Use React.useEffect instead.');
31 }
32
33 if (deps.every(isPrimitive)) {
34 throw new Error('useDeepCompareEffect should not be used with dependencies that are all primitive values. Use React.useEffect instead.');
35 }
36}
37
38function isPrimitive(val) {
39 return val == null || /^[sbn]/.test(typeof val);
40}
41/**
42 * @param value the value to be memoized (usually a dependency list)
43 * @returns a momoized version of the value as long as it remains deeply equal
44 */
45
46
47function useDeepCompareMemoize(value) {
48 var ref = React__namespace.useRef(value);
49 var signalRef = React__namespace.useRef(0);
50
51 if (!dequal.dequal(value, ref.current)) {
52 ref.current = value;
53 signalRef.current += 1;
54 } // eslint-disable-next-line react-hooks/exhaustive-deps
55
56
57 return React__namespace.useMemo(function () {
58 return ref.current;
59 }, [signalRef.current]);
60}
61
62function useDeepCompareEffect(callback, dependencies) {
63 if (process.env.NODE_ENV !== 'production') {
64 checkDeps(dependencies);
65 } // eslint-disable-next-line react-hooks/exhaustive-deps
66
67
68 return React__namespace.useEffect(callback, useDeepCompareMemoize(dependencies));
69}
70
71function useDeepCompareEffectNoCheck(callback, dependencies) {
72 // eslint-disable-next-line react-hooks/exhaustive-deps
73 return React__namespace.useEffect(callback, useDeepCompareMemoize(dependencies));
74}
75
76exports["default"] = useDeepCompareEffect;
77exports.useDeepCompareEffectNoCheck = useDeepCompareEffectNoCheck;
78exports.useDeepCompareMemoize = useDeepCompareMemoize;