1 min readupdated 3 years ago
useDebounce
The debounce method's purpose is to prevent frequently calling the time-consuming function. In the below snippet, we'll learn how to create a debounce hook using React and how to use it.
jsx
function useDebounce(value, delay) {
const [debouncedValue, setDebouncedValue] = React.useState(value);
React.useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
}, [value, delay]);
return debouncedValue;
}Usage
jsx
import useDebounce from './useDebounce.jsx';
import { useState, useEffect } from 'react'
function Search() {
const [query, setQuery] = useState('');
const [contacts, setContacts] = useState([]);
const debouncedQuery= useDebounce(query, 500);
useEffect(() => {
async function getAllContacts() {
const data = // async operation;
const filteredContacts = data.filter(value => value.includes(debouncedQuery));
setContacts(filteredContacts);
}
getAllContacts();
}, [debouncedQuery])
return (
<div>
<input type="text" value={query} onChange={(e) => setQuery(e.target.value)} />
{contacts.map((contact, index) => (
<h1 key={index}>{contact}</h1>
))}
</div>
)
}