use-watch
Version:
A react hook that use to calling the callback when a part of dependencies changed
71 lines (64 loc) • 2.09 kB
JavaScript
/**
* Bundle of use-watch
* Generated: 2021-10-10
* Version: 1.1.1
* License: MIT
* Author: 2631541504@qq.com
*/
import { useRef, useLayoutEffect } from 'react';
/**
* @param watches 依赖的集合
* 如果 watches 为引用类型,请使用 useMemo 来生成, 否则回调有可能会不停的被调用
*
* Assembly of the prop of the component
* If props is a reference type, please use useMemo to generate, otherwise the watcher may be called repeatedly
*
* @param watcher 监听回调函数
*
* map function
*
* @param [options] 选项
*
* Options
*
* @desc 请不要在 watcher 中改变依赖 watches 的值
*
* Please do not change the value of the watches in watcher
* */
function useWatch(watches, watcher) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var time = useRef({
lastCall: 0,
throttle: options.throttle,
debounce: options.debounce,
timer: null
});
var shouldCall = useRef(options.immediate);
var call = useRef({
preWatches: undefined,
watcher: watcher
});
call.current.watcher = watcher;
useLayoutEffect(function () {
var now = Date.now();
var run = function run() {
try {
call.current.watcher(watches, call.current.preWatches);
time.current.lastCall = now;
} catch (e) {
console.error(e);
}
};
if (shouldCall.current) {
if (options.debounce) {
clearTimeout(time.current.timer);
time.current.timer = setTimeout(run, options.debounce);
} else if (!options.throttle || options.throttle && now - time.current.lastCall > options.throttle) {
run();
}
}
call.current.preWatches = watches;
shouldCall.current = true;
}, [options.debounce, options.throttle, watches]);
}
export default useWatch;