UNPKG

@rooks/use-debounce

Version:
42 lines (37 loc) 1.43 kB
'use strict'; function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var react = require('react'); var debounce = _interopDefault(require('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 = react.useRef(callback); const debouncedCallbackRef = react.useRef(createDebouncedCallback(callback)); react.useEffect(() => { callbackRef.current = callback; }); react.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; } module.exports = useDebounce; //# sourceMappingURL=index.browser.cjs.js.map