UseDebounce(): Optimizing React Performance - Complete Guide
Optimizing React performance lead to app's efficiency, speed, and responsiveness. useDebounce()
allows developers to improve user experience by debouncing user input and avoiding a flood of API calls that can make the UI feel laggy or unresponsive.
Let's take a look how it work in simple terms :
useDebounce() hook allows you to wait until the user has finished typing before sending an API request or performing any expensive computation, resulting in optimized performance. This not only enhances your app's speed and efficiency but also creates a smoother and more enjoyable user experience.
How to create useDebounce() hook?
Let's do this by creating a custom hook. A custom hook help you to make your code reusable, which can improve the quality and reliability of your code.
Now! let's create a useDebounce.ts
file our .js
if you doesn't use TypeScript and paste the following code:
useDebounce() with TypeScript
import { useState, useEffect } from "react";
export const useDebounce = <T>(value: T, delay?: number): T => {
const [debouncedValue, setDebouncedValue] = useState<T>(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
// you can define a default timout on your own
}, delay || 500);
return () => {
clearTimeout(handler);
};
}, [value, delay]);
return debouncedValue;
};
useDebounce() with JavaScript
export const useDebounce = (value, delay) => {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
// you can define a default timout on your own
}, delay || 500);
return () => {
clearTimeout(handler);
};
}, [value, delay]);
return debouncedValue;
};
We define a custom hook called useDebounce that takes in two arguments: value
and delay
. The value argument represents the value you want to debounce, while the delay argument is the time in milliseconds to wait before updating the debounced value.
Inside the useEffect
hook, we use setTimeout
to delay the update of the debouncedValue
state until after the specified delay time has passed. We also include a cleanup function that clears the timeout to prevent any memory leaks.
Finally, the useDebounce
hook returns the debouncedValue state, which represents the debounced value of the original value argument.
Here is how you use it inside your component :
import { useEffect, useState } from "react";
import { useDebounce } from "../hooks/useDebounce";
export default function SearchInput() {
const [searchTerm, setSearchTerm] = useState<string>("");
// Debounce the search term
const debouncedSearchTerm = useDebounce<string>(searchTerm, 500);
useEffect(() => {
if (debouncedSearchTerm) {
// make API call with debouncedSearchTerm or any expensive computation
// ...
}
}, [debouncedSearchTerm]);
return (
<div>
<input
type="text"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
</div>
);
}
Using useDebounce() with Search Input
import React, { useState, useEffect } from "react";
import { useDebounce } from "../hooks/useDebounce";
export default function SearchInput() {
const [searchTerm, setSearchTerm] = useState<string>("");
const [results, setResults] = useState([]);
// Debounce the search term
const debouncedSearchTerm = useDebounce<string>(searchTerm, 300);
// Define the search function using useCallback
const handleSearch = async (debouncedSearchTerm: string) => {
try {
const data = await fetch(
`https://api.example.com/search?q=${debouncedSearchTerm}`
);
setResults(await data.json());
} catch (error) {
console.error(error);
}
};
// Call the search function using useEffect
useEffect(() => {
if (debouncedSearchTerm) {
handleSearch(debouncedSearchTerm);
}
}, [debouncedSearchTerm]);
return (
<div>
<input
type="text"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
<ul>
{results.map((result: any) => (
<li key={result.id}>{result.name}</li>
))}
</ul>
</div>
);
}
Suppose you have a search input in your app that sends an API request every time a user types a character. This can lead to poor performance and a suboptimal user experience if the user types too fast. To address this issue, you can use the useDebounce()
hook to add a delay between the time the user types and when the API request is sent. This results in a smoother and more responsive user experience.
Advantages of useDebounce()
The useDebounce() hook is not only useful for search inputs, but also for other scenarios where fast-changing user input is involved. It can be used to Optimize React Performance on forms, sliders, and any other components that depend on user input. By adding a delay between the time the user interacts with the component and when the change is reflected in the application, you can provide a smoother and more responsive user experience. The useDebounce() hook is a powerful tool that can help improve the performance and overall user experience of your React applications.
- Reduces the number of API requests or component updates triggered by fast-changing user input
- Improving performance and reducing unnecessary load on the server.
- Makes your application more responsive and smoother to use by avoiding a flood of updates that can make the UI feel laggy or unresponsive.
- Easy to use and customize, thanks to the flexible API of the useDebounce() hook and the variety of options it offers.
I hope this article has been useful and informative for you. If you have any questions, suggestions, or feedback, please feel free to leave them in the comments section below. I'd love to hear from you and keep improving my content based on your needs and interests. Thank you for reading!
By Mahady Manana, Fullstack Javascript Developer
21 February 2023 at 09 h 27
"Skills are honed through the interplay of learning and teaching - one must learn in order to teach, and teach in order to truly learn”. As a passionate Javascript developer, I enjoy sharing my knowledge and skills with others, and regularly publish tutorials on my website and other platforms about the latest Javascript, Typescript, Node.js, React.js, Next.js and more to help others learn and stay up to date with the latest developments trends.