Efe

Efe

SOULTEL

Full-Stack Developer & Open Source Enthusiast

Back to Snippets
TYPESCRIPTJanuary 15, 2024
React

useDebounce Hook

Debounce values in React with TypeScript

ReactTypeScriptHooksPerformance

TYPESCRIPT
import { useEffect, useState } from 'react'

export function useDebounce(value: T, delay: number): T {
  const [debouncedValue, setDebouncedValue] = useState(value)

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value)
    }, delay)

    return () => {
      clearTimeout(handler)
    }
  }, [value, delay])

  return debouncedValue
}

Usage

TYPESCRIPT
function SearchInput() {
  const [query, setQuery] = useState('')
  const debouncedQuery = useDebounce(query, 300)

  useEffect(() => {
    if (debouncedQuery) {
      // API call here
    }
  }, [debouncedQuery])

  return  setQuery(e.target.value)} />
}