altalt

How to use Debouncing in React?

posted by  Akash Sarki  on  31 January 2025

A debounce function can be used when you want to execute a function after a certain delay once the user stops trigerring it.
Let's learn how to use debouncing in React.

Implementing Debouncing in React:

We can implement debouncing with a combination of useEffect and setTimeout in React (For Functional components).

import { useState, useEffect } from "react";

function useDebounce(value, delay) {
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    return () => {
      clearTimeout(handler); // Cleanup previous timeout
    };
  }, [value, delay]);

  return debouncedValue;
}

// Usage Example
export default function DebouncedSearch() {
  const [search, setSearch] = useState("");
  const debouncedSearch = useDebounce(search, 500); // Debounce with 500ms delay

  useEffect(() => {
    if (debouncedSearch) {
      console.log("API call with:", debouncedSearch);
    }
  }, [debouncedSearch]);

  return (
    <input
      type="text"
      value={search}
      onChange={(e) => setSearch(e.target.value)}
      placeholder="Search..."
    />
  );
}

We start by creating a state variable "debouncedValue" in the above example.
We then create a "useeffect" hook, which will run when the component is initialised and when value or delay is updated.

Inside the "useeffect" hook, we declare a handler function which holds the "setTimeout" function, The setTimeout function will executes the code inside when the delay value is reached.

Suppose a user inputs a value and waits for the delay, The debounce useEffect will run saving the value in debouncedValue.

If the user inputs a value and types before the delay is reached, the cleanup function of useeffect will run clearing out all timeout functions and new setTimeout will be run saving the new value intil the delay time has reached.

Debouncing is a great way to handle re-rendering in react.

What to know about MUI? Read here.

footer company logo

Stay informed with Web Journal - Delivering fresh, reliable news and insights on the topics that matter most, all in one place.

Contact Address :

Checkpost, Siliguri
West Bengal - 734003
9883475729
akashsarki12345@gmail.com

Copyright © 2025 Web Journal. All Rights Reserved