ahooks
Version:
react hooks library
29 lines (28 loc) • 935 B
JavaScript
import { debounce } from '../utils/lodash-polyfill';
import { useMemo } from 'react';
import useLatest from '../useLatest';
import useUnmount from '../useUnmount';
import { isFunction } from '../utils';
import isDev from '../utils/isDev';
function useDebounceFn(fn, options) {
var _a;
if (isDev) {
if (!isFunction(fn)) {
console.error(`useDebounceFn expected parameter is a function, got ${typeof fn}`);
}
}
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) => {
return fnRef.current(...args);
}, wait, options), []);
useUnmount(() => {
debounced.cancel();
});
return {
run: debounced,
cancel: debounced.cancel,
flush: debounced.flush,
};
}
export default useDebounceFn;