useDebounce.ts16 lines · main
| 1 | import { useEffect, useState } from 'react' |
| 2 | |
| 3 | // consider using https://github.com/xnimorz/use-debounce |
| 4 | export function useDebounce<T>(value: T, delay?: number): T { |
| 5 | const [debouncedValue, setDebouncedValue] = useState<T>(value) |
| 6 | |
| 7 | useEffect(() => { |
| 8 | const timer = setTimeout(() => setDebouncedValue(value), delay ?? 500) |
| 9 | |
| 10 | return () => { |
| 11 | clearTimeout(timer) |
| 12 | } |
| 13 | }, [value, delay]) |
| 14 | |
| 15 | return debouncedValue |
| 16 | } |