Home
JavaScript
Debounce in JS & React
August 30, 2025
1 min

Table Of Contents

01
What is Debounce?
02
Debounce Function
03
useDebounce Hook
04
Final Thoughts

What is Debounce?

Debounce is a technique that ensures a function is only executed after a certain period of inactivity.

Example

Typing hello in a search box:

  • Without debounce → 5 API calls ❌
  • With debounce → 1 API call ✅

Debounce Function

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);
};
}

Example Usage

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

useDebounce Hook

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;
}

Example Usage

const [inputValue, setInputValue] = useState("");
const debouncedValue = useDebounce(inputValue, 500);
useEffect(() => {
if (debouncedValue) {
console.log("API call:", debouncedValue);
}
}, [debouncedValue]);

👉 The API call only triggers when the user stops typing

Final Thoughts

Debounce is a small utility, but it has a huge impact on performance and user experience.

The key is not to over-engineer it:

  • A clean, typed version is often better than a complex one
  • Choose the right pattern depending on your use case

👉 In most applications, a simple debounce is all you need.


Tags

#Javascript

Share

Related Posts

JavaScript
Prototype Inheritance
August 30, 2025
1 min
© 2026, All Rights Reserved.
Powered By

Social Media

githublinkedinyoutube