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;
react hook 实现use-watch
最新推荐文章于 2024-08-16 11:25:31 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)