Debouncing in JavaScript

Ankit Malik
3 min readAug 3, 2024

--

Debouncing is a technique used to optimize performance and avoid unnecessary processing by delaying the execution of a function until after a specified period of inactivity. It’s particularly useful in scenarios where a function could be triggered multiple times in quick succession, such as handling user input in a search box.

Let’s break down the concept of debouncing and see how it can be implemented in a React application with a custom hook.

What is Debouncing?

Imagine you’re typing a search term in a search box. Every keystroke could potentially trigger a search operation, leading to a flurry of requests or computations. This could be inefficient and overwhelming for both the server and the user interface.

Debouncing helps by postponing the execution of the search operation until the user has stopped typing for a specified period. This means that if a user types continuously, the search operation will only trigger after the user pauses typing for a moment.

Debouncing in React

To illustrate debouncing in React, let’s look at a simple example using a custom hook. The goal is to debounce the value of an input field so that a search operation only triggers when the user has paused typing for a specified delay.

Practical Implementation

Here’s a complete React example that demonstrates debouncing with a custom hook:

import { useEffect, useState } from "react";
import "./App.css";

// Custom Hook for Debounce
function useDebounce(value, delay) {
const [debounceValue, setDebounceValue] = useState(value);

useEffect(() => {
// Set the timer to delay the input value
const timerId = setTimeout(() => {
setDebounceValue(value);
}, delay);

// first Clear the timer before setting the new timer to avoid multiple timers
return () => {
clearTimeout(timerId);
};
}, [value, delay]);
return debounceValue;
}

// Main App Component
function App() {
const [inputValue, setInputValue] = useState("");
const debounceValue = useDebounce(inputValue, 1000);

return (
<div className="App">
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
placeholder="search........."
/>
<h2>Debounce value: {debounceValue}</h2>
</div>
);
}

export default App;

How It Works

  1. Custom Hook `useDebounce`:
    State Initialization: The hook maintains a state `debouncedValue` which is initialized with the input value.
    Effect Hook: The `useEffect` hook sets a timer (`setTimeout`) to update `debouncedValue` after a specified delay (`1000ms` in this case).
    Cleanup: Before setting a new timer, the existing timer is cleared (`clearTimeout`) to prevent multiple timers from being set simultaneously.
  2. Custom Hook `useDebounce`:
    State for Input: Manages the input value (`inputValue`) and updates it with every keystroke.
    Debounced Value: Uses the `useDebounce` hook to get the debounced version of the input value.
    Display: Shows the debounced value on the screen, which only updates after the user pauses typing for a second.

Benefits of Debouncing

Performance Improvement: Reduces the number of function calls, making your application more efficient.
User Experience: Provides a smoother and more responsive experience by avoiding unnecessary updates and computations.

By using the `useDebounce` hook, you can easily integrate debouncing into your React applications, optimizing performance and enhancing user experience.

--

--

Ankit Malik

Machine Learning enthusiast and MERN Stack Developer!