useDebouncedValue

Debounce a changing value to prevent unnecessary updates.


✅ Features

  • Ideal for search inputs and filters
  • Delays updates by your defined time
  • Reacts to value changes only after delay

📦 Usage

1import { useDebouncedValue } from './useDebouncedValue';
2
3const [input, setInput] = useState('');
4const debouncedInput = useDebouncedValue(input, 500);
5
6useEffect(() => {
7  if (debouncedInput) {
8    fetchSearchResults(debouncedInput);
9  }
10}, [debouncedInput]);

📋 Source Code

This is the full implementation of useDebouncedValue

1import { useEffect, useState } from 'react';
2
3export function useDebouncedValue<T>(value: T, delay: number): T {
4  const [debounced, setDebounced] = useState<T>(value);
5
6  useEffect(() => {
7    const timer = setTimeout(() => setDebounced(value), delay);
8    return () => clearTimeout(timer);
9  }, [value, delay]);
10
11  return debounced;
12}
13