dotUI
dotUI
beta
  1. Hooks
  2. Browser hooks
  3. useDebounce

useDebounce

Delay the execution of function or state update with useDebounce.

"use client";

import * as React from "react";
import { SearchIcon } from "lucide-react";
import { TextField } from "@/lib/components/core/default/text-field";
import { useDebounce } from "@/lib/hooks/use-debounce";

function Demo() {
  const [searchInput, setSearchInput] = React.useState("");
  const debouncedValue = useDebounce(searchInput, 1000);

  return (
    <div className="w-full max-w-sm">
      <div className="relative">
        <SearchIcon
          size={18}
          className="pointer-events-none absolute left-2 top-1/2 -translate-y-1/2 transform text-fg-muted"
        />
        <TextField
          value={searchInput}
          onChange={(value) => {
            setSearchInput(value);
          }}
          placeholder="Search"
          className="full-w pl-8"
        />
      </div>
      <div className="mt-10 text-center">
        {debouncedValue ? (
          <p>Results for &quot;{debouncedValue}&quot;</p>
        ) : (
          <p className="text-fg-muted">Start searching</p>
        )}
      </div>
    </div>
  );
}

Installation

Copy and paste the following code into your project.

import React from "react";

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

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

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

  return debouncedValue;
}

Update the import paths to match your project setup.

Arguments

NameTypeDescription
value
any
The value that you want to debounce. This can be of any type.
delay
number
The delay time in milliseconds. After this amount of time, the latest value is used.

Return value

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

Built by mehdibha. The source code is available on GitHub.