-
-
Save Alimjanov-Ibragim/7c321780ae89350eb99cff9fb00d4d04 to your computer and use it in GitHub Desktop.
This hook will allow me to debounce any function that I want to run after a certain delay. For example, if I have an input field that triggers a search function on every keystroke, this hook will prevent unnecessary API calls by delaying the search function until the user stops typing for a certain period.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useEffect } from 'react'; | |
export const useDebounce = (value, delay) => { | |
const [debouncedValue, setDebouncedValue] = useState(value); | |
useEffect(() => { | |
const timer = setTimeout(() => { | |
setDebouncedValue(value); | |
}, delay); | |
return () => { | |
clearTimeout(timer); | |
}; | |
}, [value, delay]); | |
return debouncedValue; | |
}; | |
//============ Usage | |
import { useDebounce } from './useDebounce'; | |
import { useState, useEffect } from 'react'; | |
export const SearchBar = ()=> { | |
// Custom hook to debounce search term changes | |
const debouncedSearchTerm = useDebounce(searchTerm, 500); | |
const [searchTerm, setSearchTerm] = useState(""); | |
const [results, setResults] = useState([]); | |
// Function to fetch search results from API | |
async function fetchSearchResults() { | |
try { | |
const response = await fetch(`/api/search?q=${debouncedSearchTerm}`); | |
const data = await response.json(); | |
setResults(data); | |
} catch (error) { | |
console.error(error); | |
} | |
}; | |
useEffect(() => { | |
fetchSearchResults(); | |
}, [debouncedSearchTerm]); | |
return ( | |
<> | |
<input type="text" value={searchTerm} onChange={(event) => setSearchTerm(event.target.value)} | |
placeholder="Search..."/> | |
<ul>{results.map((result) => (<li key={crypto.randomUUID()}>{result.name}</li>))}</ul> | |
</> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment