UNPKG

1.46 kBJavaScriptView Raw
1"use strict";
2
3exports.__esModule = true;
4exports.default = void 0;
5
6var _react = require("react");
7
8var _useMounted = _interopRequireDefault(require("./useMounted"));
9
10function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
11
12function useCustomEffect(effect, dependencies, isEqualOrOptions) {
13 var isMounted = (0, _useMounted.default)();
14
15 var _ref = typeof isEqualOrOptions === 'function' ? {
16 isEqual: isEqualOrOptions
17 } : isEqualOrOptions,
18 isEqual = _ref.isEqual,
19 _ref$effectHook = _ref.effectHook,
20 effectHook = _ref$effectHook === void 0 ? _react.useEffect : _ref$effectHook;
21
22 var dependenciesRef = (0, _react.useRef)();
23 dependenciesRef.current = dependencies;
24 var cleanupRef = (0, _react.useRef)(null);
25 effectHook(function () {
26 // If the ref the is `null` it's either the first effect or the last effect
27 // ran and was cleared, meaning _this_ update should run, b/c the equality
28 // check failed on in the cleanup of the last effect.
29 if (cleanupRef.current === null) {
30 var cleanup = effect();
31
32 cleanupRef.current = function () {
33 if (isMounted() && isEqual(dependenciesRef.current, dependencies)) {
34 return;
35 }
36
37 cleanupRef.current = null;
38 if (cleanup) cleanup();
39 };
40 }
41
42 return cleanupRef.current;
43 });
44 (0, _react.useDebugValue)(effect);
45}
46
47var _default = useCustomEffect;
48exports.default = _default;
\No newline at end of file