How to use Debounce in React (Lodash)

How to use Debounce in React (Lodash)

An explanation of the debounce function and how to use it in your React Application

As a user typing in an input field or performing a particular action - an efficient method of making requests from the API is to allow for user action to be completed before interacting with the API. This prevents your UI code from needing to process every event and also drastically reduces the number of calls sent to your server.

One of the solutions to this is to use debounce/throttle, and a Lodash provides us with the debounce function. Lodash’s debounce function delays invoking a function passed into it; It can help performance in some situations.

In this article, we would be taking a look at the right implementation of debounce in a React App.

Our App

Let's take this sample React Application that contains a search input field and each time the user types a request is made that loads the data into the UI.

export default function App() {
  const [users, setUsers] = React.useState([]);

  async function search(value) {
    const res = await fetch(
      // Fake API 
      `https://api.github.com/?search=${value}`
    );
    const body = await res.json();
    return body.results.map((result) => result.name);
  }

  async function handleChange(event) {
    setUsers(await search(event.target.value));
  }

  return (
    <div className="App">
      <input
        type="search"
        placeholder="Enter your search"
        onChange={handleChange}
      />
      <ul>
        {users.map((user) => (
          <li key={user.id}>{user.firstname}</li>
        ))}
      </ul>
    </div>
  );
}

With the above code, the search request is made every time the user makes a keystroke in the input element. Ideally, we want the search request to be made only when the user has stopped typing. We can use the debounce function from Lodash to do this. The debounce function delays the processing of the key-up event until the user has stopped typing for a predetermined amount of time.

Implementing Debounce in React

npm install lodash

Create a debounce function, and call it inside of the handlechange, a timer is set to the debounced function that determines the intervals between each call.

import { debounce } from 'lodash';

const handleSearchDebounce = debounce(async (value) => {
    setUser(await search(value));
}, 300);

async function handleChange(event) {
  handleSearchDebounce(event.target.value);
}

Approach 2

With the first method, a new version of the debounced method is created on every render. We can use the useRef hook to store the debounced function across renders instead:

import { debounce } from 'lodash';

const handleSearchDebounce = React.useRef(
  debounce(async (value) => {
    setUsers(await search(value));
  }, 300)
).current;

/* We can use the `useEffect` hook to cancel the debounced function 
so whenever the component unmounts the search stops running, and
the function gets canceled */
React.useEffect(() => {
  return () => {
    handleSearchDebounce.cancel();
  };
}, [handleSearchDebounce]);

Conclusion

In this article, I showed you how to implement a debounce function in React using Lodash. However, you don’t need to use Lodash's implementation of debounce in your projects if you don’t want to. You can decide to write your own debounce function and some other libraries offer this same debounce function.

👉🏾 Learn more about me

👉🏾 Connect on LinkedIn

👉🏾 Subscribe to my blog, let's feast