@rooks/use-debounce
Version:
Debounce hook for react
38 lines (35 loc) • 1.26 kB
JavaScript
import { useRef, useEffect } from 'react';
import debounce from 'lodash.debounce';
/**
* Debounce hook
* @param {function} callback The callback to debounce
* @param {number} wait The duration to debounce
* @returns {function} The debounced callback
*/
function useDebounce(callback, wait, options) {
function createDebouncedCallback(fn) {
return debounce(fn, wait, options);
}
const callbackRef = useRef(callback);
const debouncedCallbackRef = useRef(createDebouncedCallback(callback));
useEffect(() => {
callbackRef.current = callback;
});
useEffect(() => {
debouncedCallbackRef.current = createDebouncedCallback((...args) => {
callbackRef.current(...args);
});
}, [wait, options]);
function debouncedCallbackWithEventPersist(...args) {
args.forEach(arg => {
if (!(arg instanceof Event) && arg.nativeEvent instanceof Event) {
// Synthetic events need to be persisted
arg.persist();
}
});
return debouncedCallbackRef.current(...args);
}
return debouncedCallbackWithEventPersist;
}
export default useDebounce;
//# sourceMappingURL=index.browser.esm.js.map