Skip to content

Instantly share code, notes, and snippets.

@Alimjanov-Ibragim
Forked from ali-sabry/useDebounce.js
Created March 27, 2023 08:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Alimjanov-Ibragim/7c321780ae89350eb99cff9fb00d4d04 to your computer and use it in GitHub Desktop.
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.
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