Reputation: 185
I need a bit of help here, I am new to react and I have this doubt.
I am not getting a working example of a to AutoComplete with debounce
. i.e. my AutoComplete component is delaying in displaying entered text and while I am searching the solution for this I got to know we can overcome this by using AutoComplete with debounce. So please anyone can help with this by adding debounce to given sandbox link OR can suggest to me why it is delaying while displaying the entered text. Thank you.
Reference: https://codesandbox.io/s/crazy-galois-5v1mi
Upvotes: 1
Views: 15590
Reputation: 186
I tried the existing answers for this question (given by Fatemeh Qasemkhani and justuff), but it didn't work for some reason.
Had to do a bit more research and found the below article : How to Correctly Debounce and Throttle Callbacks in React
Below code is similar to the code I used to implement this feature :
import { useEffect, useMemo } from 'react';
import debounce from 'lodash.debounce';
function MyComponent() {
const handleSearch = () => {
// handle the search event...
};
const debouncedChangeHandler = useMemo(
() => debounce(handleSearch , 300), []
);
// Stop the invocation of the debounced function
// after unmounting
useEffect(() => {
return () => {
debouncedChangeHandler.cancel();
}
}, []);
return (
<div>
<AutoComplete
...,
onSearch={debouncedChangeHandler}
/>
</div>
);
}
Upvotes: 1
Reputation: 238
Adding debounce inline will often result in triggering on each keystroke.
If you want to debounce after the user has finished their key strokes then you will need to use useCallback
.
Example -
const debouncedSearch = useCallback(
debounce(nextValue => onSearch(nextValue), 1000),
[], // will be created only once initially
);
const handleSearch = event => {
event.persist();
const { value: nextValue } = event.target;
// Even though handleSearch is created on each render and executed
// it references the same debouncedSearch that was created initially
debouncedSearch(nextValue);
};
<AutoComplete
...,
onSearch={handleSearch}
/>
I found this article useful and a recommended read. https://www.freecodecamp.org/news/debounce-and-throttle-in-react-with-hooks/
Upvotes: 7
Reputation: 2042
Use debounce method from lodash.
import debounce from 'lodash/debounce';
<AutoComplete
...,
onSearch={debounce(handleSearch, 300)} // 300 is your required delay
/>
Upvotes: 7