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

What is the best way to add a debounce effect on field in react/react native?

I am trying to add a debounce effect on my useEffect as of right now, as soon as value in input changes it start to call the function inside it.

useEffect(() => {
   if (inputValue.length > 0) {
       fn();
   }
}, [inputValue]);

Any suggestion how I can improve or implement a debounce effect here.

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

>Solution :

Here is a simple useDebounceEffect:

const useDebounceEffect = (fnc, deps, delay) => {
  const ref = useRef();

  useEffect(() => {
    clearTimeout(ref.current);
    ref.current = setTimeout(() => {
      fnc();
      clearTimeout(ref.current);
    }, delay);
  }, [...deps, fnc, delay]);
};

Make use of a ref to keep the timer id.
Pass the delay as an argument.

Link

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