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

@er-raj-aryan/use-smart-debounce

v0.1.2

Published

Modern React hooks for debouncing values, callbacks, and async functions — with TypeScript support, cancellation, and stale-response protection.

Readme

@er-raj-aryan/use-smart-debounce

Modern React hooks for smarter debouncing — built for real-world apps.
Lightweight, TypeScript-ready, and async-safe. Perfect for search inputs, autocomplete, or any case where you need to wait for users to stop typing before doing work.

NPM Version NPM Downloads License Bundle Size GitHub License GitHub Repo Stars

Why this package?

Most debounce hooks either:

  • 💥 Break on async calls
  • ⚙️ Don’t cancel stale API requests
  • 🧩 Or require too much setup

This package fixes that — giving you three clean hooks that just work:

  1. useDebouncedValue — debounces simple values
  2. useDebouncedCallback — debounces functions/event handlers (leading/trailing/maxWait)
  3. useDebouncedAsync — debounced async calls with cancellation + stale-response protection

All in <3 KB, zero dependencies.

Install

npm i @er-raj-aryan/use-smart-debounce

or

yarn add @er-raj-aryan/use-smart-debounce

got you. here’s a drop-in README section that adds clear, copy-paste usage examples for all three hooks (including a real MUI Autocomplete wired to your HS Code API). paste this below your Install section (or replace your README with the whole thing).

Quick Start

// App.tsx or any React component
import { useDebouncedValue } from "@er-raj-aryan/use-smart-debounce";
import { useEffect, useState } from "react";

export default function Demo() {
  const [q, setQ] = useState("");
  const dq = useDebouncedValue(q, 500); // wait 500ms after typing stops

  useEffect(() => {
    if (!dq) return;
    // call your API here with dq
    console.log("Search for:", dq);
  }, [dq]);

  return (
    <input
      value={q}
      onChange={(e) => setQ(e.target.value)}
      placeholder="Type…"
    />
  );
}

Exports

import {
  useDebouncedValue,
  useDebouncedCallback,
  useDebouncedAsync,
} from "@er-raj-aryan/use-smart-debounce";
  • useDebouncedValue<T>(value: T, delay?: number): T

  • useDebouncedCallback(fn, delay?: number, opts?: { leading?: boolean; trailing?: boolean; maxWait?: number })

  • useDebouncedAsync(fn, delay?: number, opts?: { leading?: boolean; trailing?: boolean; maxWait?: number })


1) useDebouncedValue — debounce any value

Use cases: text inputs, sliders, filters — whenever a value should “settle” before you react.

import { useDebouncedValue } from "@er-raj-aryan/use-smart-debounce";
import { useEffect, useState } from "react";

function PriceFilter() {
  const [price, setPrice] = useState(0);
  const debouncedPrice = useDebouncedValue(price, 300);

  useEffect(() => {
    // expensive query only after 300ms of inactivity
    console.log("Fetch using price:", debouncedPrice);
  }, [debouncedPrice]);

  return (
    <input
      type="number"
      value={price}
      onChange={(e) => setPrice(Number(e.target.value))}
      min={0}
    />
  );
}

2) useDebouncedCallback — debounce any function/handler

Use cases: onChange, onResize, onScroll, or any callback you don’t want to fire too often.

import { useDebouncedCallback } from "@er-raj-aryan/use-smart-debounce";
import { useState } from "react";

function SearchLogger() {
  const [q, setQ] = useState("");

  const logTyped = useDebouncedCallback(
    (value: string) => {
      console.log("User typed:", value);
    },
    400,
    { leading: false, trailing: true } // call after pause
  );

  return (
    <input
      value={q}
      onChange={(e) => {
        setQ(e.target.value);
        logTyped(e.target.value);
      }}
      placeholder="Type…"
    />
  );
}

Methods:

  • debounced.cancel() — cancel pending call
  • debounced.flush(...args) — immediately invoke now
logTyped.cancel();
logTyped.flush("force run now");

3) useDebouncedAsync — debounce async calls (cancel + stale-safe)

Use cases: live search, autocomplete, server-side lookups.

  • Cancels previous in-flight promise.
  • Ignores stale responses (race-condition safe).
import { useDebouncedAsync } from "@er-raj-aryan/use-smart-debounce";
import { useEffect, useState } from "react";

function LiveSearch() {
  const [q, setQ] = useState("");

  const { run, status, data, error } = useDebouncedAsync(
    async (query: string) => {
      if (query.length < 3) return [];
      const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`);
      return res.json();
    },
    500, // wait 500ms after user stops typing
    { trailing: true }
  );

  useEffect(() => {
    run(q);
  }, [q]);

  return (
    <div>
      <input value={q} onChange={(e) => setQ(e.target.value)} />
      {status === "loading" && <p>Loading…</p>}
      {error && <p style={{ color: "red" }}>Error</p>}
      <pre>{JSON.stringify(data, null, 2)}</pre>
      {/* Also available: run.cancelInFlight() */}
    </div>
  );
}

API Reference

useDebouncedValue<T>(value: T, delay = 300): T

Returns a debounced copy of value that updates after delay ms of inactivity.

useDebouncedCallback(fn, delay = 300, opts?)

  • leading?: boolean — fire immediately on first call in a burst (default false)
  • trailing?: boolean — fire after the last call in a burst (default true)
  • maxWait?: number — ensure execution after this time even if calls continue

Also exposes:

  • cancel() — cancel pending call
  • flush(...args) — invoke immediately

useDebouncedAsync(fn, delay = 300, opts?)

Same options as above. Returns:

  • run(...args) — debounced async runner (also has cancelInFlight())
  • Getters: status ("idle" | "loading" | "success" | "error"), data, error

Import Notes

  • ESM:

    import { useDebouncedValue } from "@er-raj-aryan/use-smart-debounce";
  • CommonJS:

    const { useDebouncedValue } = require("@er-raj-aryan/use-smart-debounce");

SSR (Next.js)

These hooks are client-side by nature. In Next.js 13+/App Router, put components using them under a "use client" file boundary.

"use client";
import { useDebouncedValue } from "@er-raj-aryan/use-smart-debounce";

Troubleshooting

  • TypeScript DTS error in your app Ensure you’re on TypeScript ≥ 5.4 and React types ≥ 18.
  • No results while typing Check your condition (query.length < 3) and the API path.
  • Old results flashing Use useDebouncedAsync (it cancels/ignores stale responses).

License

MIT © 2025 Er Raj Aryan