I am using useEffect and its working fine, but I am aked to use debounce insted. Should I just make the useEffect into a seprate/ reusable function?
const [query, setQuery] = useState('');
useEffect(() => {
const delayDebounceFn = setTimeout(() => {
// Perform search operation
console.log(`Searching for: ${query}`);
}, 1000); // Delay search by 1 second
return () => clearTimeout(delayDebounceFn);
}, [query]);
const handleInputChange = (event) => {
setQuery(event.target.value);
};
3
Answers
To answer your question: Yes.
Go for useEffect function, if data to be fetched or manipulated when dependent object changes
but in cases like, user is typing in searchbar then it make sense to delay the fetching of records for ,let’s say, microseconds.
Hope this helps
Throttling regulates the frequency of function execution, ensuring it doesn’t occur more frequently than a specified interval. However, with useEffect and setTimeout, you can delay a function call to occur after a designated time period.
For instance, in a search scenario, when typing to search for records with the name "Sau," throttling would limit the function invocation to once per second. On the other hand, using useEffect with setTimeout, the function would be triggered every second.
and for it to work you should use Loadash
You can split and separate the debounce function from useEffect and call that debounce function from it.
The better way to handle search functions is to use a debounce function(with time delay) for searching. Please check the example code below,