@react-hook/debounce
Version:
A React hook for debouncing setState and other callbacks
57 lines (43 loc) • 1.58 kB
JavaScript
import { useRef, useEffect, useCallback, useState } from 'react';
import useLatest from '@react-hook/latest';
var useDebounceCallback = function useDebounceCallback(callback, wait, leading) {
if (wait === void 0) {
wait = 100;
}
if (leading === void 0) {
leading = false;
}
var storedCallback = useLatest(callback);
var timeout = useRef();
var deps = [wait, leading, storedCallback]; // Cleans up pending timeouts when the deps change
function _ref() {
timeout.current && clearTimeout(timeout.current);
timeout.current = void 0;
}
useEffect(() => _ref, deps);
function _ref2() {
timeout.current = void 0;
}
return useCallback(function () {
// eslint-disable-next-line prefer-rest-params
var args = arguments;
var {
current
} = timeout; // Calls on leading edge
if (current === void 0 && leading) {
timeout.current = setTimeout(_ref2, wait); // eslint-disable-next-line prefer-spread
return storedCallback.current.apply(null, args);
} // Clear the timeout every call and start waiting again
current && clearTimeout(current); // Waits for `wait` before invoking the callback
timeout.current = setTimeout(() => {
timeout.current = void 0;
storedCallback.current.apply(null, args);
}, wait);
}, deps);
};
var useDebounce = (initialState, wait, leading) => {
var state = useState(initialState);
return [state[0], useDebounceCallback(state[1], wait, leading), state[1]];
};
export { useDebounce, useDebounceCallback };
//# sourceMappingURL=index.dev.mjs.map