-
Notifications
You must be signed in to change notification settings - Fork 0
/
useUpdateOnly.ts
32 lines (26 loc) · 916 Bytes
/
useUpdateOnly.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
import { DependencyList, useEffect, useRef } from 'react';
import { Comparator, UpdateCallback } from '../types';
import { useDependencyList } from '../useDependencyList/useDependencyList';
export const useUpdateOnly = (
callback: UpdateCallback,
dependencyList: DependencyList,
comparator?: boolean | Comparator<DependencyList, DependencyList>
): void => {
const initialDependencyListRef = useRef(dependencyList);
const dependencies = useDependencyList(dependencyList, comparator);
useEffect(() => {
if (initialDependencyListRef.current === dependencies) {
return;
}
const result = callback();
return () => {
(async () => {
const func = await result;
if (typeof func === 'function') {
await func();
}
})();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, dependencies);
};