UNPKG

@jvitela/recompute

Version:

Selector functions based on Observable and Computed values.

69 lines (53 loc) 1.6 kB
"use strict"; exports.__esModule = true; exports.useComputation = void 0; var _react = require("react"); var _reactRedux = require("react-redux"); var refsCount = 0; var addRef = function addRef(selector) { if (!selector.refIds) { selector.refIds = []; } selector.refIds.push(++refsCount); return refsCount; }; var removeRef = function removeRef(selector, refId) { if (!selector.refIds) { return; } selector.refIds = selector.refIds.filter(function (id) { return id !== refId; }); if (selector.refIds.length === 0) { // console.log("clearing cache"); selector.clearCache(); } }; /** * Wrapper around useSelector that keeps reference count per component instance * in order to automatically clear the cache when all components using * the selector are unmounted. * * @param Function selector * @param {...any} args */ var useComputation = function useComputation(selector) { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var ref = (0, _react.useRef)(); if (!ref.current) { ref.current = addRef(selector); } (0, _react.useEffect)(function () { var refId = ref.current; return function () { return removeRef(selector, refId); }; }, [selector]); var result = (0, _reactRedux.useSelector)(function (state) { return selector.withState(state).apply(null, args); }); // console.log(`Recomputations: ${selector.recomputations()}`); return result; }; exports.useComputation = useComputation;