common-hook
Version:
提供项目中常用的 React Hooks
35 lines (34 loc) • 944 B
JavaScript
import { useMemo } from "react";
import { useLatest, useUnmount } from "common-hook";
import { debounce } from "common-screw";
/**
* @name 处理防抖函数的Hook
* @description
* 在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时
* @example
* const { run } = useDebounceFn(
() => {
setValue(value + 1)
},
{
wait: 500
}
)
*/
export const useDebounceFn = (fn, options) => {
var _a;
const fnRef = useLatest(fn);
const wait = (_a = options === null || options === void 0 ? void 0 : options.wait) !== null && _a !== void 0 ? _a : 1000;
const debounced = useMemo(() => debounce((...args) => {
// @ts-ignore
return fnRef.current(...args);
}, wait, options), []);
useUnmount(() => {
debounced.cancel();
});
return {
run: debounced,
cancel: debounced.cancel,
flush: debounced.flush
};
};