Skip to content
← Snippets

useDebounce Hook

Debounce a fast-changing value like input or search queries.

Sep 4, 2022 · 1 min read

When you want to limit how often a function or value updates — like search input typing — you can debounce it.

Debouncing is a common technique to improve performance, especially when dealing with APIs or heavy operations triggered by user input.


Code

useDebounce.ts
import { useState, useEffect } from 'react';
 
export function useDebounce<T>(value: T, delay = 500) {
  const [debouncedValue, setDebouncedValue] = useState(value);
 
  useEffect(() => {
    const handler = setTimeout(() => setDebouncedValue(value), delay);
    return () => clearTimeout(handler);
  }, [value, delay]);
 
  return debouncedValue;
}
useDebounce Hook | Viren Soni | Software Engineer