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