Getting Started
Accordion
Barricade Tape
Buttons
Browser Window
Contact Section
File Stack
Glass Grid
NewGooey Words
Glowing Dots Background
Image Pile
Jelly Loader
Mask Cursor Effect
NewMagnet Tabs
Masonry Grid
Pixelated Carousel
NewPixelated Text
NewPrismatic Haze Background
Projects Section
Proximity Background
Proximity Lift Grid
Skeumorphic Music Card
Spotlight Grid
Texts
Trading Card
Wavy Background
NewDebounce
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.
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;