useDebounce
useDebounce
is a custom hook that allows you to debounce any fast changing
value.
Import#
import { useDebounce } from '@dwarvesf/react-hooks'
Return value#
The useDebounce
hook returns the result of the last func invocation. Note that
it will return undefined
if there are no previous invocations.
Usage#
function Example() {// Usagefunction App() {// State and setters for ...// Search termconst [searchTerm, setSearchTerm] = useState('')// API search resultsconst [results, setResults] = useState([])// Searching status (whether there is pending API request)const [isSearching, setIsSearching] = useState(false)// Debounce search term so that it only gives us latest value ...// ... if searchTerm has not been updated within last 500ms.// The goal is to only have the API call fire when user stops typing ...// ... so that we aren't hitting our API rapidly.const debouncedSearchTerm = useDebounce(searchTerm, 500)// Effect for API calluseEffect(() => {if (debouncedSearchTerm) {setIsSearching(true)searchCharacters(debouncedSearchTerm).then((results) => {setIsSearching(false)setResults(results)})} else {setResults([])setIsSearching(false)}},[debouncedSearchTerm], // Only call effect if debounced search term changes)return (<Stack direction="column" spacing="10px"><Inputplaceholder="Search repositories"onChange={(e) => setSearchTerm(e.target.value)}/>{isSearching && <Spinner size="sm" />}{results.length > 0 && (<Box><UnorderedList pr="20px">{results.map((result) => (<ListItem key={result.id}>{result.name}</ListItem>))}</UnorderedList></Box>)}</Stack>)}// API search functionfunction searchCharacters(search) {const apiKey = 'f9dfb1e8d466d36c27850bedd2047687'return fetch(`https://api.github.com/search/repositories?per_page=5&q=${search}`,{method: 'GET',},).then((r) => r.json()).then((r) => r.items).catch((error) => {console.error(error)return []})}return <App />}
Parameters#
The useDebounce
hook accepts following params:
Name | Type | Default | Description |
---|---|---|---|
value | any | _ | |
delay | number | _ | The delay time in milliseconds. |