useDebounce

A React hook to delay the execution of a function or state update.

Overview

useDebounce is essential for handling fast-changing values like search inputs or window resizing. It ensures that your logic only runs after the user has stopped interacting for a specified duration, significantly improving performance.

Demo

Interactive Preview

useDebounce

Optimizing performance by delaying updates until after a burst of activity.

Search Optimization

Type something below. The debounced value will update 500ms after you stop typing.

Immediate Value
Empty
Debounced Value
Waiting...
Delay: 500ms

Think about search bars, window resizing, or form validation.

API Reference

function useDebounce<T>(value: T, delay: number): T

Parameters

NameTypeDescription
valueTThe value you want to debounce (can be any type)
delaynumberThe delay in milliseconds

Usage Examples

Search Input Debounce

import { useState } from 'react'
import { useDebounce } from 'react-hooks-ts'
 
function SearchComponent() {
  const [searchTerm, setSearchTerm] = useState('')
  const debouncedSearch = useDebounce(searchTerm, 500)
 
  // Use debouncedSearch for API calls
  return (
    <input 
      value={searchTerm} 
      onChange={(e) => setSearchTerm(e.target.value)} 
    />
  )
}

Features

  • Performance - Prevents unnecessary renders and API calls.
  • 🎯 Generic - Works with any data type (strings, numbers, objects).
  • 🧩 Zero Dependencies - Lightweight implementation with standard React hooks.
  • 🛡️ Race Condition Safe - Ensures only the latest value is preserved.