Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Debounce function called multiple times

I call following function within useEffect.

useEffect(() => {
  loadData();
}, [amount]);

loadData function uses Lodash debounce function. When I update amount from input, loadData gets called several times depending on length of amount string.

const loadData = useCallback(
  debounce(() => {
    console.log('called!');

    // Fetch data from API ...
  }, 1000),
  [amount]
);

In spite of using useCallback hook and 1s debounce. It returns multiple times. How to fix it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks in advance

>Solution :

When amount changes, the useCallback generates a new function with a new debounce timer. To solve that pass amount a parameter to the function, and remove amount from the deps array of the useCallback:

const loadData = useCallback(
  debounce((amount) => {
    console.log('called!', amount);

    // Fetch data from API ...
  }, 1000),
  []
);

useEffect(() => {
  loadData(amount);
}, [amount]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading