useDebounce.ts 426 B

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