UNPKG

ahooks

Version:
48 lines (47 loc) 1.83 kB
import { useRef } from 'react'; import useUnmount from '../useUnmount'; import depsAreSame from './depsAreSame'; import { getTargetElement } from './domTarget'; const createEffectWithTarget = (useEffectType) => { /** * * @param effect * @param deps * @param target target should compare ref.current vs ref.current, dom vs dom, ()=>dom vs ()=>dom */ const useEffectWithTarget = (effect, deps, target) => { const hasInitRef = useRef(false); const lastElementRef = useRef([]); const lastDepsRef = useRef([]); const unLoadRef = useRef(undefined); useEffectType(() => { var _a; const targets = Array.isArray(target) ? target : [target]; const els = targets.map((item) => getTargetElement(item)); // init run if (!hasInitRef.current) { hasInitRef.current = true; lastElementRef.current = els; lastDepsRef.current = deps; unLoadRef.current = effect(); return; } if (els.length !== lastElementRef.current.length || !depsAreSame(lastElementRef.current, els) || !depsAreSame(lastDepsRef.current, deps)) { (_a = unLoadRef.current) === null || _a === void 0 ? void 0 : _a.call(unLoadRef); lastElementRef.current = els; lastDepsRef.current = deps; unLoadRef.current = effect(); } }); useUnmount(() => { var _a; (_a = unLoadRef.current) === null || _a === void 0 ? void 0 : _a.call(unLoadRef); // for react-refresh hasInitRef.current = false; }); }; return useEffectWithTarget; }; export default createEffectWithTarget;