Search code examples
javascriptreactjsreact-nativedebouncing

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.


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