useDebounce

All about useDebounce hook in React


Delay the executation of a function.

Usage

function ReactComponent() {
  const [value, setValue] = useState('')
 
  const fnDebounced = useDebounce(setValue, 500)
 
  return (
    <div>
      <p>Debounced value: {value}</p>
 
      <input
        type="text"
        defaultValue={value}
        onChange={event => fnDebounced(event.target.value)}
      />
    </div>
  )
}

Hook

type DebounceFunction = <T extends never[]>(
  func: (...args: T) => void,
  delay: number,
) => (...args: T) => void
 
export const useDebounce: DebounceFunction = (func, delay) => {
  let timeoutId: NodeJS.Timeout | null
 
  return (...args) => {
    if (timeoutId) {
      clearTimeout(timeoutId)
    }
 
    timeoutId = setTimeout(() => {
      func(...args)
      timeoutId = null
    }, delay)
  }
}