Back to library
⚛️Reacttypescriptintermediate

useDebounce Hook

React hook to debounce any value

hooksperformanceoptimization

Code

1import { useState, useEffect } from 'react';
2
3function useDebounce<T>(value: T, delay: number): T {
4  const [debouncedValue, setDebouncedValue] = useState<T>(value);
5
6  useEffect(() => {
7    const handler = setTimeout(() => {
8      setDebouncedValue(value);
9    }, delay);
10
11    return () => {
12      clearTimeout(handler);
13    };
14  }, [value, delay]);
15
16  return debouncedValue;
17}
18
19// Usage example
20function SearchComponent() {
21  const [searchTerm, setSearchTerm] = useState('');
22  const debouncedSearchTerm = useDebounce(searchTerm, 500);
23
24  useEffect(() => {
25    if (debouncedSearchTerm) {
26      // Perform search with debouncedSearchTerm
27      console.log('Searching for:', debouncedSearchTerm);
28    }
29  }, [debouncedSearchTerm]);
30
31  return (
32    <input
33      type="text"
34      value={searchTerm}
35      onChange={(e) => setSearchTerm(e.target.value)}
36      placeholder="Search..."
37    />
38  );
39}

Quick Tips

  • Click the "Copy" button to copy the code to your clipboard
  • This code is production-ready and can be used in your projects
  • Check out related snippets below for more examples

Related Snippets

Build Your Own Snippet Library

Organize your team's code snippets with Snippetly. Share knowledge and boost productivity across your organization.