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

28 lines
796 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)
}
}
2024-10-24 20:30:56 +00:00
const DEFAULT_DEPS = []
export default function useDebounceCallback (fn, time, deps = DEFAULT_DEPS) {
2023-10-06 01:33:14 +00:00
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), [])
}