Skip to content

Instantly share code, notes, and snippets.

@hyber1z0r
Last active August 4, 2020 09:39
Show Gist options
  • Save hyber1z0r/c50497052058bbc900d53c574cfac024 to your computer and use it in GitHub Desktop.
Save hyber1z0r/c50497052058bbc900d53c574cfac024 to your computer and use it in GitHub Desktop.
useDebounce example
import React, { useState, useEffect } from 'react';
import useDebounce from './useDebounce';
const Search = () => {
const [searchTerm, setSearchTerm] = useState('');
const [results, setResults] = useState([]);
// ✅ Use debounce hook to debounced searchTerm as it is rapidly changing
const debouncedSearchTerm = useDebounce(searchTerm, 500);
// Effect only runs when debouncedSearchTerm changes,
// and it only does when the user stops typing for more than 500ms
useEffect(() => {
if (debouncedSearchTerm) {
const fetchResults = async () => {
const response = await fetch(`/search?q=${debouncedSearchTerm}`);
const json = await response.json();
setResults(json);
}
fetchResults();
}
}, [debouncedSearchTerm]);
return (
<>
<input value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} />
<ul>
{results.map((result) => <li>{result.title}</li>)}
</ul>
</>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment