React hook to debounce any value
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}Organize your team's code snippets with Snippetly. Share knowledge and boost productivity across your organization.