Circle Menu
Dialog Form
Dominoes List Scroll
Dominoes Scroll Indicator
Eagle Vision
Electric AI Input
File Input
Flip Scroll
Glowing Scroll Indicator
Horizontal Scroll
Icon Wheel
Image Pile
Interactive CTA
Interactive Folder
Interest Picker
Jelly Loader
Leave Rating
Mask Cursor Effect
Magnet Tabs
Masonry Grid
OTP Input
Photo Gallery
Pixelated Carousel
Rolling Ball Scroll Indicator
Rubik Cube
Sidebar
Sine Wave
Skeumorphic Music Card
Social Media Card
Stacked Input Form
Stack Scroll
Trading Card
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.
Follow below steps 👇🏻
useDebounce Hook
Add the useDebounce hook to your custom hooks collection by copying the code below.
import { useState, useEffect } from "react";
function useDebounce<T>(value: T, delay: number): T {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
}, [value, delay]);
return debouncedValue;
}
export default useDebounce;
Usage
import { useState } from "react";
import useDebounce from "./useDebounce";
function SearchComponent() {
const [searchTerm, setSearchTerm] = useState("");
const debouncedSearch = useDebounce(searchTerm, 500);
useEffect(() => {
// ? Debounced search value will change after 500ms of no input,
// ? and that's when the API call will be made
// ? This prevents API calls on every keystroke
if (debouncedSearch) {
console.log("API Call with: ", debouncedSearch);
}
}, [debouncedSearch]);
return (
<input
type="text"
placeholder="Search..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
);
}
export default SearchComponent;