beautiful-react-hooks
Version:
A collection of beautiful (and hopefully useful) React hooks to speed-up your components and hooks development
25 lines (24 loc) • 910 B
JavaScript
import { useCallback, useEffect, useRef } from 'react';
import debounce from 'lodash.debounce';
import useWillUnmount from './useWillUnmount';
const defaultOptions = {
leading: false,
trailing: true,
};
/**
* Accepts a function and returns a new debounced yet memoized version of that same function that delays
* its invoking by the defined time.
* If time is not defined, its default value will be 250ms.
*/
const useDebouncedCallback = (fn, dependencies, wait = 600, options = defaultOptions) => {
const debounced = useRef(debounce(fn, wait, options));
useEffect(() => {
debounced.current = debounce(fn, wait, options);
}, [fn, wait, options]);
useWillUnmount(() => {
var _a;
(_a = debounced.current) === null || _a === void 0 ? void 0 : _a.cancel();
});
return useCallback(debounced.current, dependencies);
};
export default useDebouncedCallback;