2023-10-06 20:01:51 +00:00
|
|
|
import { useCallback, useState } from 'react'
|
|
|
|
import useNoInitialEffect from './use-no-initial-effect'
|
2023-10-06 01:33:14 +00:00
|
|
|
|
|
|
|
export function debounce (fn, time) {
|
|
|
|
let timeoutId
|
|
|
|
return wrapper
|
|
|
|
function wrapper (...args) {
|
|
|
|
if (timeoutId) {
|
|
|
|
clearTimeout(timeoutId)
|
|
|
|
}
|
|
|
|
timeoutId = setTimeout(() => {
|
|
|
|
timeoutId = null
|
|
|
|
fn(...args)
|
|
|
|
}, time)
|
|
|
|
// return a function that clears the timeout for use in useEffect cleanup
|
|
|
|
return () => clearTimeout(timeoutId)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default function useDebounceCallback (fn, time, deps = []) {
|
|
|
|
const [args, setArgs] = useState([])
|
2023-10-06 02:14:57 +00:00
|
|
|
const memoFn = useCallback(fn, deps)
|
2023-10-06 21:34:16 +00:00
|
|
|
useNoInitialEffect(debounce(() => memoFn(...args), time), [memoFn, time, args])
|
2023-10-06 01:33:14 +00:00
|
|
|
return useCallback((...args) => setArgs(args), [])
|
|
|
|
}
|