How to Debounce a Function in React.js


How can we debounce function calls in React.js?

We can easily use a debounce function from lodash or our own.

1. Install lodash.debounce

First, let’s install debounce from lodash (not the entire library).

npm install lodash.debounce --save

2. Use debounce from input’s onChange() handler

We can import debounce and use it to trigger a function after a certain number of milliseconds (1000ms in this code).

import debounce from "lodash.debounce";
const SomeComponent = () => {
  const [value, setValue] = useState("");
  const someApiCall = debounce((value) => {
    // Debounced
  }, 1000);
  return <>
    <input
      value={value}
      onChange={(e) => {
        someApiCall(e.target.value);
        setValue(e.target.value);
      }}
    />
  </>

2.1 Debounce leading option

By default, debounce triggers the function at the end of the interval.

So if we call someApiCall() three times in 1000ms, then it will trigger the final function call.

someApiCall('a');
someApiCall('b');
someApiCall('c'); // 'c'

We can tell this debounce function to trigger at the beginning of the interval using the leading flag. This means the function is executed immediately, but not again until the delay has passed.

someApiCall('a');
someApiCall('b');
someApiCall('c'); // 'a'

In lodash, it can be specified in the third parameter.

const someApiCall = debounce((value) => {
  // Debounced
}, 1000, { leading: true });

3. Our own debounce function

If we don’t want to use lodash, we can write our own debounce function.

function debounce(func, wait) {
  let timeout;
  return function() {
    const context = this;
    const args = arguments;
    const later = function() {
      timeout = null;
      func.apply(context, args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
};