CoastalCommitsPastes/client/lib/hooks/use-debounce.ts

18 lines
362 B
TypeScript
Raw Normal View History

import { useState, useEffect } from "react"
2022-03-23 19:28:39 -04:00
export default function useDebounce<T>(value: T, delay: number) {
const [debouncedValue, setDebouncedValue] = useState(value)
2022-03-23 19:28:39 -04:00
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value)
}, delay)
2022-03-23 19:28:39 -04:00
return () => {
clearTimeout(handler)
}
}, [value, delay])
2022-03-23 19:28:39 -04:00
return debouncedValue
2022-03-23 19:28:39 -04:00
}