@winglet/react-utils
Version:
React utility library providing custom hooks, higher-order components (HOCs), and utility functions to enhance React application development with improved reusability and functionality
35 lines (32 loc) • 1.1 kB
JavaScript
import { useRef, useMemo } from 'react';
import { isObject } from '@winglet/common-utils/filter';
import { getTypeTag } from '@winglet/common-utils/lib';
import { equals } from '@winglet/common-utils/object';
const useSnapshot = (input, omit) => {
const snapshotRef = useSnapshotReference(input, omit);
return snapshotRef.current;
};
const useSnapshotReference = (input, omit) => {
const snapshotRef = useRef(input);
const typeRef = useRef(getTypeTag(input));
const omitRef = useRef(omit && (omit instanceof Set ? omit : new Set(omit)));
return useMemo(() => {
if ((typeRef.current === getTypeTag(input) && isEmpty(input)) ||
equals(snapshotRef.current, input, omitRef.current))
return snapshotRef;
snapshotRef.current = input;
return snapshotRef;
}, [input]);
};
const isEmpty = (value) => {
if (!value)
return true;
else if (isObject(value)) {
for (const _ in value)
return false;
return true;
}
else
return false;
};
export { useSnapshot, useSnapshotReference };