common-hook
Version:
提供项目中常用的 React Hooks
33 lines (32 loc) • 953 B
JavaScript
import { useMemo } from "react";
import { useUnmount, useLatest } from "common-hook";
import { throttle } from "common-screw";
/**
* @name 处理函数节流的Hook
* @description
* 规定在时间内,只能触发一次函数。如果这个时间内触发多次函数,只有一次生效
* @example
* const { run } = useThrottleFn(
() => {
setValue(value + 1);
},
{ wait: 500 },
);
*/
export const useThrottleFn = (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 throttled = useMemo(() => throttle((...args) => {
// @ts-ignore
return fnRef.current(...args);
}, wait, options), []);
useUnmount(() => {
throttled.cancel();
});
return {
run: throttled,
cancel: throttled.cancel,
flush: throttled.flush
};
};