Last active
August 4, 2020 09:39
-
-
Save hyber1z0r/c50497052058bbc900d53c574cfac024 to your computer and use it in GitHub Desktop.
useDebounce example
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 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