VayuUI

useDebounce

A hook to delay the update of a value until a specified time has passed.

The useDebounce hook allows you to debounce any fast-changing value. The debounced value will only reflect the latest value when the useDebounce hook has not been called for the specified time period.

This is particularly useful for optimizing performance for:

  • Search inputs that trigger API calls
  • Form validation
  • Window resize calculations
  • Heavy computations

Demo

Real-time Value:

Debounced Value:

Source Code

Copy this code into src/hooks/useDebounce.ts:

import { useState, useEffect } from 'react';

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

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

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

  return debouncedValue;
};

Usage

import { useState, useEffect } from 'react';
import { useDebounce } from '@/hooks/useDebounce';

const SearchComponent = () => {
  const [searchTerm, setSearchTerm] = useState('');
  const debouncedSearchTerm = useDebounce(searchTerm, 500);

  useEffect(() => {
    if (debouncedSearchTerm) {
      // Trigger API call here
      console.log('Searching for:', debouncedSearchTerm);
    }
  }, [debouncedSearchTerm]);

  return (
    <input
      type="text"
      value={searchTerm}
      onChange={(e) => setSearchTerm(e.target.value)}
      placeholder="Search..."
    />
  );
};

API Reference

Parameters

NameTypeDescription
valueTThe value to be debounced.
delaynumberThe delay in milliseconds to wait before updating the value.

Return Value

TypeDescription
TThe debounced value.

On this page