forked from streamich/react-use
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseCustomCompareEffect.ts
41 lines (32 loc) · 1.19 KB
/
useCustomCompareEffect.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import { DependencyList, EffectCallback, useEffect, useRef } from 'react';
const isPrimitive = (val: any) => val !== Object(val);
type DepsEqualFnType<TDeps extends DependencyList> = (prevDeps: TDeps, nextDeps: TDeps) => boolean;
const useCustomCompareEffect = <TDeps extends DependencyList>(
effect: EffectCallback,
deps: TDeps,
depsEqual: DepsEqualFnType<TDeps>
) => {
if (process.env.NODE_ENV !== 'production') {
if (!(deps instanceof Array) || !deps.length) {
console.warn(
'`useCustomCompareEffect` should not be used with no dependencies. Use React.useEffect instead.'
);
}
if (deps.every(isPrimitive)) {
console.warn(
'`useCustomCompareEffect` should not be used with dependencies that are all primitive values. Use React.useEffect instead.'
);
}
if (typeof depsEqual !== 'function') {
console.warn(
'`useCustomCompareEffect` should be used with depsEqual callback for comparing deps list'
);
}
}
const ref = useRef<TDeps | undefined>(undefined);
if (!ref.current || !depsEqual(deps, ref.current)) {
ref.current = deps;
}
useEffect(effect, ref.current);
};
export default useCustomCompareEffect;