score:5

Accepted answer

use debounce method from lodash.

import debounce from 'lodash/debounce';

<autocomplete
  ...,
  onsearch={debounce(handlesearch, 300)} // 300 is your required delay
/>

score:5

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/


Related Query

More Query from same tag