import { useEffect, useRef } from 'react';
const defaultCompare = (prev, next) => prev === next;
export const useWatch = (
callback,
value,
{ initialValue = '', compare = defaultCompare } = {},
) => {
const prevValue = useRef(initialValue);
const safeEffects = useRef([]);
const prev = prevValue.current;
if (!compare(prev, value)) {
const safeEffect =
callback === null || callback === void 0 ? void 0 : callback(prev);
if (typeof safeEffect === 'function') {
safeEffects.current.push(safeEffect);
}
prevValue.current = value;
}
useEffect(() => {
safeEffects.current.forEach((safeEffect) => safeEffect());
safeEffects.current = [];
});
};
export default useWatch;