0

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.

Ubaid
  • 737
  • 8
  • 18
  • `debounce(fn)`? – evolutionxbox Oct 12 '22 at 10:38
  • Does this answer your question? [How to perform debounce?](https://stackoverflow.com/questions/23123138/how-to-perform-debounce) – KcH Oct 12 '22 at 10:38
  • No, it does not. I am trying to find a way to create a hook which can be used like a useEffect (let's say useDebounceEffect) for debouncing. – Ubaid Oct 12 '22 at 10:40
  • 1
    https://usehooks.com/useDebounce/ and https://github.com/xnimorz/use-debounce may be of help – evolutionxbox Oct 12 '22 at 10:42
  • Great, it works. Thank you! @evolutionxbox I will write my own hook using this idea https://usehooks.com/useDebounce/. – Ubaid Oct 12 '22 at 10:49

1 Answers1

1

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

Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39