useDebounce

useDebounce

It is a custom React hook that returns a debounced version of a value passed to it as an argument, with a default delay of 500ms.

Props

  • value : The value that needs to be debounced. It can be of any type.

  • delay (optional) : delay in milliseconds before updating the debounced value. Default value is 500ms.

Returns

The debounced version of the passed value.

The Hook

useDebounce.ts
import { useState, useEffect } from 'react'
 
export function useDebounce<T>(value: T, delay: number = 500): T {
  const [debounceValue, setDebounceValue] = useState<T>(value)
 
  useEffect(() => {
    const handler = setTimeout(() => setDebounceValue(value), delay)
 
    return () => {
      clearTimeout(handler)
    }
  }, [value, delay])
 
  return debounceValue
}

Usage

UseDebounceDemo.tsx
import { useState, ChangeEvent } from 'react'
import { useDebounce } from './useDebounce'
 
export const UseDebounceDemo = () => {
  const [searchParam, setSearchParam] = useState<string>('')
 
  const searchDebounce = useDebounce(searchParam, 400)
 
  const handlerSearch = (event: ChangeEvent<HTMLInputElement>) => {
    setSearchParam(event.target.value)
  }
 
  return (
    <div>
      <input type='text' onChange={handlerSearch} />
      <p>Without debounce :{searchParam}</p>
      <p>Debounce Value :{searchDebounce}</p>
    </div>
  )
}