The best and most reliable approach to perform a debounce in React is by using the debounce function from Lodash, a popular utility library. This method prevents a function from being called too often, which is especially useful for tasks like handling user input or API calls during typing.
Steps to Implement Debounce with lodash.debounce
Install Lodash (if you haven't already):
npm install lodash
Implement Debounce in a component:
import React, { useState, useCallback } from 'react';
import debounce from 'lodash/debounce';
function SearchComponent() {
const [query, setQuery] = useState('');
// Debounced function to handle the search logic
const debouncedSearch = useCallback(
debounce((searchTerm) => {
console.log("Searching for:", searchTerm);
// You can call an API or perform search here
}, 500), // 500ms debounce delay
[]
);
const handleInputChange = (event) => {
setQuery(event.target.value);
debouncedSearch(event.target.value);
};
return (
<div>
<input
type="text"
value={query}
onChange={handleInputChange}
placeholder="Search..."
/>
</div>
);
}
export default SearchComponent;