import { useCallback, useMemo } from 'react' import { debounce } from 'lodash' export const useAsyncDebounced = (callback, time) => { const debounced = useMemo( () => debounce( (res, rej, ...args) => callback(...args) .then(res) .catch(rej), time ), [callback, time] ) const debouncedCallback = useCallback( (...args) => new Promise((res, rej) => { debounced(res, rej, ...args) }), [debounced] ) return debouncedCallback } /* Usage: const deboucedAsync = useAsyncDebouncedCallback((v) => fetch('search?query=' + v), 300) With async hooks: const { result, isLoading } = useAsyncCallback(deboucedAsync, [...]) */