npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@usefy/use-debounce

v0.2.6

Published

A React hook for value debouncing with leading/trailing edge and maxWait options

Downloads

131

Readme


Overview

@usefy/use-debounce is a powerful React hook for debouncing values with advanced options like leading edge, trailing edge, and maximum wait time. Perfect for search inputs, form validation, API calls, and any scenario where you need to limit the rate of value updates.

Part of the @usefy ecosystem — a collection of production-ready React hooks designed for modern applications.

Why use-debounce?

  • Zero Dependencies — Pure React implementation with no external dependencies
  • TypeScript First — Full type safety with generics and exported interfaces
  • Flexible Options — Leading edge, trailing edge, and maxWait support
  • SSR Compatible — Works seamlessly with Next.js, Remix, and other SSR frameworks
  • Lightweight — Minimal bundle footprint (~400B minified + gzipped)
  • Well Tested — Comprehensive test coverage with Vitest

Installation

# npm
npm install @usefy/use-debounce

# yarn
yarn add @usefy/use-debounce

# pnpm
pnpm add @usefy/use-debounce

Peer Dependencies

This package requires React 18 or 19:

{
  "peerDependencies": {
    "react": "^18.0.0 || ^19.0.0"
  }
}

Quick Start

import { useDebounce } from "@usefy/use-debounce";

function SearchInput() {
  const [query, setQuery] = useState("");
  const debouncedQuery = useDebounce(query, 300);

  useEffect(() => {
    if (debouncedQuery) {
      searchAPI(debouncedQuery);
    }
  }, [debouncedQuery]);

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

API Reference

useDebounce<T>(value, delay?, options?)

A hook that returns a debounced version of the provided value.

Parameters

| Parameter | Type | Default | Description | | --------- | -------------------- | ------- | ---------------------------------- | | value | T | — | The value to debounce | | delay | number | 500 | The debounce delay in milliseconds | | options | UseDebounceOptions | {} | Additional configuration options |

Options

| Option | Type | Default | Description | | ---------- | --------- | ------- | --------------------------------------------- | | leading | boolean | false | Update on the leading edge (first call) | | trailing | boolean | true | Update on the trailing edge (after delay) | | maxWait | number | — | Maximum time to wait before forcing an update |

Returns

| Type | Description | | ---- | ------------------- | | T | The debounced value |


Examples

Basic Search Input

import { useDebounce } from "@usefy/use-debounce";

function SearchInput() {
  const [query, setQuery] = useState("");
  const debouncedQuery = useDebounce(query, 300);
  const [results, setResults] = useState([]);

  useEffect(() => {
    async function search() {
      if (!debouncedQuery.trim()) {
        setResults([]);
        return;
      }
      const data = await fetch(`/api/search?q=${debouncedQuery}`);
      setResults(await data.json());
    }
    search();
  }, [debouncedQuery]);

  return (
    <div>
      <input
        value={query}
        onChange={(e) => setQuery(e.target.value)}
        placeholder="Type to search..."
      />
      <ul>
        {results.map((result) => (
          <li key={result.id}>{result.name}</li>
        ))}
      </ul>
    </div>
  );
}

With Leading Edge (Instant First Update)

import { useDebounce } from "@usefy/use-debounce";

function FilterPanel() {
  const [filters, setFilters] = useState({ category: "all", price: 0 });

  // Update immediately on first change, then debounce subsequent changes
  const debouncedFilters = useDebounce(filters, 500, { leading: true });

  useEffect(() => {
    applyFilters(debouncedFilters);
  }, [debouncedFilters]);

  return (
    <div>
      <select
        value={filters.category}
        onChange={(e) =>
          setFilters((f) => ({ ...f, category: e.target.value }))
        }
      >
        <option value="all">All</option>
        <option value="electronics">Electronics</option>
        <option value="clothing">Clothing</option>
      </select>
      <input
        type="range"
        value={filters.price}
        onChange={(e) => setFilters((f) => ({ ...f, price: +e.target.value }))}
      />
    </div>
  );
}

With maxWait (Guaranteed Updates)

import { useDebounce } from "@usefy/use-debounce";

function AutoSaveEditor() {
  const [content, setContent] = useState("");

  // Debounce for 1 second, but guarantee save every 5 seconds during continuous typing
  const debouncedContent = useDebounce(content, 1000, { maxWait: 5000 });

  useEffect(() => {
    if (debouncedContent) {
      saveToServer(debouncedContent);
    }
  }, [debouncedContent]);

  return (
    <textarea
      value={content}
      onChange={(e) => setContent(e.target.value)}
      placeholder="Start typing... (auto-saves)"
    />
  );
}

Form Validation

import { useDebounce } from "@usefy/use-debounce";

function RegistrationForm() {
  const [username, setUsername] = useState("");
  const [error, setError] = useState("");
  const debouncedUsername = useDebounce(username, 500);

  useEffect(() => {
    async function checkAvailability() {
      if (debouncedUsername.length < 3) {
        setError("Username must be at least 3 characters");
        return;
      }
      const response = await fetch(
        `/api/check-username?u=${debouncedUsername}`
      );
      const { available } = await response.json();
      setError(available ? "" : "Username is already taken");
    }

    if (debouncedUsername) {
      checkAvailability();
    }
  }, [debouncedUsername]);

  return (
    <div>
      <input
        value={username}
        onChange={(e) => setUsername(e.target.value)}
        placeholder="Choose a username"
      />
      {error && <span className="error">{error}</span>}
    </div>
  );
}

Debouncing Object Values

import { useDebounce } from "@usefy/use-debounce";

function FilteredTable() {
  const [filters, setFilters] = useState({
    search: "",
    status: "all",
    sortBy: "date",
  });

  const debouncedFilters = useDebounce(filters, 300);

  useEffect(() => {
    fetchTableData(debouncedFilters);
  }, [debouncedFilters]);

  return (
    <div>
      <input
        value={filters.search}
        onChange={(e) => setFilters((f) => ({ ...f, search: e.target.value }))}
        placeholder="Search..."
      />
      <select
        value={filters.status}
        onChange={(e) => setFilters((f) => ({ ...f, status: e.target.value }))}
      >
        <option value="all">All</option>
        <option value="active">Active</option>
        <option value="inactive">Inactive</option>
      </select>
    </div>
  );
}

TypeScript

This hook is written in TypeScript with full generic support.

import { useDebounce, type UseDebounceOptions } from "@usefy/use-debounce";

// Generic type inference
const debouncedString = useDebounce("hello", 300); // string
const debouncedNumber = useDebounce(42, 300); // number
const debouncedObject = useDebounce({ x: 1 }, 300); // { x: number }

// Explicit generic type
interface Filters {
  search: string;
  category: string;
}
const debouncedFilters = useDebounce<Filters>(filters, 300);

Testing

This package maintains comprehensive test coverage to ensure reliability and stability.

Test Coverage

📊 View Detailed Coverage Report (GitHub Pages)

Test Categories

  • Initialize with initial value
  • Initialize with different types (string, number, boolean, object, array)
  • Use default delay of 500ms
  • Update immediately with leading: true
  • Do not update immediately with leading: false (default)
  • Update on trailing edge with trailing: true (default)
  • No update with trailing: false
  • Combined leading and trailing options
  • Force update after maxWait even with continuous changes
  • Respect maxWait when delay is longer
  • Work correctly with both leading and maxWait

License

MIT © mirunamu

This package is part of the usefy monorepo.