MCPcopy Create free account
hub / github.com/alibaba/hooks / createEffectWithTarget

Function createEffectWithTarget

packages/hooks/src/utils/createEffectWithTarget.ts:8–62  ·  view source on GitHub ↗
(useEffectType: typeof useEffect | typeof useLayoutEffect)

Source from the content-addressed store, hash-verified

6import { getTargetElement } from './domTarget';
7
8const createEffectWithTarget = (useEffectType: typeof useEffect | typeof useLayoutEffect) => {
9 /**
10 *
11 * @param effect
12 * @param deps
13 * @param target target should compare ref.current vs ref.current, dom vs dom, ()=>dom vs ()=>dom
14 */
15 const useEffectWithTarget = (
16 effect: EffectCallback,
17 deps: DependencyList,
18 target: BasicTarget<any> | BasicTarget<any>[],
19 ) => {
20 const hasInitRef = useRef(false);
21
22 const lastElementRef = useRef<(Element | null)[]>([]);
23 const lastDepsRef = useRef<DependencyList>([]);
24
25 const unLoadRef = useRef<ReturnType<EffectCallback>>(undefined);
26
27 useEffectType(() => {
28 const targets = Array.isArray(target) ? target : [target];
29 const els = targets.map((item) => getTargetElement(item));
30
31 // init run
32 if (!hasInitRef.current) {
33 hasInitRef.current = true;
34 lastElementRef.current = els;
35 lastDepsRef.current = deps;
36
37 unLoadRef.current = effect();
38 return;
39 }
40
41 if (
42 els.length !== lastElementRef.current.length ||
43 !depsAreSame(lastElementRef.current, els) ||
44 !depsAreSame(lastDepsRef.current, deps)
45 ) {
46 unLoadRef.current?.();
47
48 lastElementRef.current = els;
49 lastDepsRef.current = deps;
50 unLoadRef.current = effect();
51 }
52 });
53
54 useUnmount(() => {
55 unLoadRef.current?.();
56 // for react-refresh
57 hasInitRef.current = false;
58 });
59 };
60
61 return useEffectWithTarget;
62};
63
64export default createEffectWithTarget;

Calls

no outgoing calls

Tested by

no test coverage detected