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

28 lines
796 B
JavaScript
Raw Normal View History

2023-10-06 15:01:51 -05:00
import { useCallback, useState } from 'react'
import useNoInitialEffect from './use-no-initial-effect'
2023-10-05 20:33:14 -05: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)
}
}
2024-10-24 15:30:56 -05:00
const DEFAULT_DEPS = []
export default function useDebounceCallback (fn, time, deps = DEFAULT_DEPS) {
2023-10-05 20:33:14 -05:00
const [args, setArgs] = useState([])
2023-10-05 21:14:57 -05:00
const memoFn = useCallback(fn, deps)
2023-10-06 16:34:16 -05:00
useNoInitialEffect(debounce(() => memoFn(...args), time), [memoFn, time, args])
2023-10-05 20:33:14 -05:00
return useCallback((...args) => setArgs(args), [])
}