Logo

Implement useDebouncedValue

Could you implement a TypeScript React hook useDebouncedValue and show how I'd use it to debounce a search input?

I will create a generic hook with a configurable delay, clear timers on changes/unmount, and demonstrate usage with a search field.

  • Define hook signature: useDebouncedValue<T>(value: T, delayMs?: number): T
  • Use useEffect + setTimeout to update debounced value after delay
  • Clear timeout on value/delay change and on unmount to avoid leaks
  • Show example with an input field debounced before firing a query

Hook

import { useEffect, useRef, useState } from 'react'

export function useDebouncedValue<T>(value: T, delayMs = 300): T {
  const [debouncedValue, setDebouncedValue] = useState<T>(value)
  const timeoutRef = useRef<number | null>(null)

  useEffect(() => {
    if (timeoutRef.current !== null) {
      window.clearTimeout(timeoutRef.current)
    }

    timeoutRef.current = window.setTimeout(() => {
      setDebouncedValue(value)
    }, delayMs)

    return () => {
      if (timeoutRef.current !== null) {
        window.clearTimeout(timeoutRef.current)
      }
    }
  }, [value, delayMs])

  return debouncedValue
}

Usage

import { useState } from 'react'
// import { useDebouncedValue } from './use-debounced-value'

export function SearchInput() {
  const [query, setQuery] = useState('')
  const debouncedQuery = useDebouncedValue(query, 400)

  // Pretend to fetch when debouncedQuery changes
  // useEffect(() => {
  //   fetch(`/api/search?q=\$\{encodeURIComponent(debouncedQuery)}`)
  // }, [debouncedQuery])

  return (
    <div>
      <input
        value={query}
        onChange={(e) => setQuery(e.target.value)}
        placeholder="Search components..."
      />
      <p>Debounced: {debouncedQuery}</p>
    </div>
  )
}
Code
Artificial Intelligence | Chakra UI Pro