Debounce is a technique that ensures a function is only executed after a certain period of inactivity.
Typing hello in a search box:
Use this when you want to control when a function executes, such as event handlers.
function debounce<T extends (...args: unknown[]) => void>(fn: T,delay = 500) {let timer: ReturnType<typeof setTimeout>;return (...args: Parameters<T>) => {clearTimeout(timer);timer = setTimeout(() => {fn(...args);}, delay);};}
const handleSearch = debounce((value: string) => {console.log("Searching:", value);}, 500);input.addEventListener("input", (e) => {handleSearch((e.target as HTMLInputElement).value);});
👉 The function only runs after the user stops typing
In React, we often deal with state, not just functions. That’s where a debounce hook becomes useful.
import { useEffect, useState } from "react";function useDebounce<T>(value: T, delay = 500): T {const [debouncedValue, setDebouncedValue] = useState(value);useEffect(() => {const timer = setTimeout(() => {setDebouncedValue(value);}, delay);return () => clearTimeout(timer);}, [value, delay]);return debouncedValue;}
const [inputValue, setInputValue] = useState("");const debouncedValue = useDebounce(inputValue, 500);useEffect(() => {if (debouncedValue) {console.log("API call:", debouncedValue);}}, [debouncedValue]);