stacker.news/components/use-debounce-callback.js

26 lines
761 B
JavaScript
Raw Normal View History

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), [])
}