Skip to content

useDebounce

React hook to delay the execution of function or state update.

Add the hook via the CLI:

sh
npx @novajslabs/cli add useDebounce
sh
npx @novajslabs/cli add useDebounce
sh
pnpm dlx @novajslabs/cli add useDebounce

Or copy and paste the code into your project:

ts
import { useEffect, useState } from "react";

export const useDebounce = <T>(value: T, delay: number) => {
  const [debouncedValue, setDebouncedValue] = useState<T>(value);

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

    return () => {
      clearTimeout(handleTimeout);
    };
  }, [value, delay]);

  return debouncedValue;
};
js
import { useEffect, useState } from "react";

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

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

    return () => {
      clearTimeout(handleTimeout);
    };
  }, [value, delay]);

  return debouncedValue;
};

Requirements

React 16.8 or higher

Parameters

value required

  • Type: any

The value that you want to debounce.

delay required

  • Type: number

The delay time in milliseconds. After this time, the latest value is used.

Return values

debouncedValue

  • Type: any

The debounced value. After the delay time has passed without the value changing, this will be updated to the latest value.

Example

tsx
import { useState } from "react";
import { useDebounce } from "./hooks/useDebounce";

const fruits = [
  "Apple",
  "Banana",
  "Mango",
  "Grapes",
  "Papaya",
  "Coconut",
  "Guava",
  "Orange",
  "Pineapple",
  "Watermelon",
];

const App = () => {
  const [searchTerm, setSearchTerm] = useState("");
  const debouncedSearchTerm = useDebounce(searchTerm, 500);

  const filteredFruits = fruits.filter((fruit) =>
    fruit.toLowerCase().includes(debouncedSearchTerm.toLowerCase())
  );

  return (
    <div>
      <input
        type="text"
        placeholder="Search..."
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)}
      />
      <ul>
        {filteredFruits.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
    </div>
  );
};

export default App;

Use cases

Here are some use cases where this React hook is useful:

  • Debouncing a search input to avoid excessive API calls
  • Delaying the execution of a function to wait for user pause in typing
  • Reducing the frequency of state updates in response to user actions
  • Improving performance by limiting the number of renders caused by fast-changing values

Released under the MIT License.