Stackbits
Utilities > Debounce

Debounce

Debouncing is a technique used to improve performance by delaying the execution of a function until after a specified time has passed since the last invocation. This is especially useful for optimizing search inputs, API calls, and event listeners.

See it in Action 👇🏻

Without Debounce, API will be called on every input

Bad

With Debounce, API will be called after x-ms of no input

Good

Follow below steps 👇🏻

useDebounce Hook

Add the useDebounce hook to your custom hooks collection by copying the code below.

1
import { useState, useEffect } from "react";
2
3
function useDebounce<T>(value: T, delay: number): T {
4
const [debouncedValue, setDebouncedValue] = useState(value);
5
6
useEffect(() => {
7
const handler = setTimeout(() => {
8
setDebouncedValue(value);
9
}, delay);
10
11
return () => {
12
clearTimeout(handler);
13
};
14
}, [value, delay]);
15
16
return debouncedValue;
17
}
18
19
export default useDebounce;

Usage

1
import { useState } from "react";
2
import useDebounce from "./useDebounce";
3
4
function SearchComponent() {
5
const [searchTerm, setSearchTerm] = useState("");
6
const debouncedSearch = useDebounce(searchTerm, 500);
7
8
useEffect(() => {
9
// ? Debounced search value will change after 500ms of no input,
10
// ? and that's when the API call will be made
11
// ? This prevents API calls on every keystroke
12
if (debouncedSearch) {
13
console.log("API Call with: ", debouncedSearch);
14
}
15
}, [debouncedSearch]);
16
17
return (
18
<input
19
type="text"
20
placeholder="Search..."
21
value={searchTerm}
22
onChange={(e) => setSearchTerm(e.target.value)}
23
/>
24
);
25
}
26
27
export default SearchComponent;

⭐️ Got a question or feedback?
Feel free to reach out!