Stackbits is going through a refresh! Some features may not be available. Follow @stackbitss on twitter for updates.
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.

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;