Optimizing React Performance with useDebounce.
Tags: react, performance, debounce, optimisation
Published: 2023-12-23 16:57:59

The term “**debounce**” might sound technical, but its concept is like a traffic light for signals in the world of software development. Imagine you’re at a busy intersection, and there’s a button to cross the road. If you press and release it quickly, the system might get confused, thinking you pressed it multiple times.

Debouncing is giving the system a short break. Picture the traffic light saying, “Wait a sec, let’s make sure the person wants to cross before changing the signal again” In software development, this concept is crucial when dealing with heavy tasks, such as numerous API calls, where efficiency is key.

### The Initial Approach

```
import { useEffect, useState } from "react";
import { getUsers } from "./api";
import User from "./type";
import "./styles.css";

export default function App2() {
  const [search, setSearch] = useState<string>("");
  const [loading, setLoading] = useState<boolean>(false);
  const [user, setUser] = useState<User[]>([]);

  useEffect(() => {
    const loadUsers = async () => {
      setLoading(true);
      const users = await getUsers(search);
      setUser(users?.users);
      setLoading(false);
    };

    loadUsers();
  }, [search]);

  const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearch(e.target.value);
  };

  return (
    <div className="App">
      <input type="text" value={search} onChange={handleSearch} />
      {loading ? (
        <>Loading...</>
      ) : (
        user.map((user) => <h2 key={user.id}>{user?.firstName}</h2>)
      )}
    </div>
  );
}
```

Let’s take a look at a React code snippet above that searches a list of users based on user input. While this code works as you can see in the output below, it listens to every keystroke, leading to potentially unnecessary API calls and reduced performance.
{% embed https://www.loom.com/share/c308d5d28e604c6aa65e34d6bf57c76c?sid=12bef1c2-3d86-47e1-9847-964c4ce0525e %}

### Introducing Debounce for Performance

To tackle this issue, we introduced the concept of debounce and created a custom hook, useDebounce, to delay updates to a value until a specified time has passed since the last update.

```
import { useEffect, useState } from "react";

export const useDebouce = <T>(value: T, delay = 500) => {
  const [deboucedValue, setDebouncedValue] = useState<T>(value);

  useEffect(() => {
    const timeout = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    return () => clearTimeout(timeout);
  }, [value, delay]);

  return deboucedValue;
};
```
Now, using this custom hook to our React component.

```
import { useEffect, useState } from "react";
import { getUsers } from "./api";
import User from "./type";
import { useDebouce } from "./hooks";
import "./styles.css";

export default function App() {
  const [search, setSearch] = useState<string>("");
  const [loading, setLoading] = useState<boolean>(false);
  const [user, setUser] = useState<User[]>([]);
  const debouncedSearch = useDebouce(search);

  useEffect(() => {
    const loadUsers = async () => {
      setLoading(true);
      const users = await getUsers(debouncedSearch);
      setUser(users?.users);
      setLoading(false);
    };

    loadUsers();
  }, [debouncedSearch]);

  const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearch(e.target.value);
  };

  return (
    <div className="App">
      <input type="text" value={search} onChange={handleSearch} />
      {loading ? (
        <>Loading...</>
      ) : (
        user.map((user) => <h2 key={user.id}>{user?.firstName}</h2>)
      )}
    </div>
  );
}
```
we can observe a significant improvement as you can see in the output video below. The API call is triggered only when the user stops typing, enhancing the overall efficiency of the app.

{% embed https://www.loom.com/share/bc71f399c02b41c89af83ba35010158d?sid=d093cc3b-96af-4716-935e-2c490d69944f %}

### Why It Matters?

Implementing search functionality is a common requirement in applications. Humans typically type more than one character every 500ms. By applying debounce, we can reasonably assume that the user has finished typing if there’s been no input for 500ms, optimizing the application’s performance.


### Conclusion
In conclusion, understanding and applying debounce can greatly enhance the performance of your React applications. By incorporating the `useDebounce` hook, you can strike a balance between responsiveness and efficiency, ensuring a smoother user experience.

Try implementing debounce in your projects and share your experiences. The optimization possibilities are vast, and by mastering these concepts, you empower yourself to build more performant and responsive applications.

---
Connect with me to stay updated on more tips and tricks for efficient coding! Follow me on [GitHub](https://github.com/Alwaz) for the latest repositories and projects. Let’s connect on [LinkedIn](https://www.linkedin.com/in/alwaz-qazi/) to share insights and collaborate on exciting ventures.

Happy coding!
>