Tired of making a dozen API calls every time a user types three letters?
Meet @er-raj-aryan/use-smart-debounce โ a lightweight React hook library that makes debouncing async-safe, TypeScript-ready, and smooth like butter ๐ง
๐ NPM: @er-raj-aryan/use-smart-debounce
๐ GitHub: https://github.com/er-raj-aryan/use-smart-debounce
๐ก Why I Built This
While building a Next.js dashboard, I ran into the same old issue โ API calls firing on every keystroke during search input.
Existing solutions like lodash.debounce or use-debounce didnโt handle async calls, cancellation, or stale responses well.
So I decided to build something that does:
- Cancels stale API requests
- Handles async promises safely
- Works with
leading,trailing, andmaxWaitmodes - Comes with full TypeScript support
- Ships with zero dependencies
โ๏ธ Installation
npm i @er-raj-aryan/use-smart-debounce # or yarn add @er-raj-aryan/use-smart-debounce ๐งฉ Whatโs Inside
| Hook | Use Case | Description |
|---|---|---|
useDebouncedValue | Debounce values | Returns a delayed version of any state value |
useDebouncedCallback | Debounce functions | Debounce any callback with leading/trailing control |
useDebouncedAsync | Debounce async calls | Cancels in-flight requests & ignores stale responses |
๐ง Basic Example โ Debounce a Value
import { useDebouncedValue } from "@er-raj-aryan/use-smart-debounce"; import { useState, useEffect } from "react"; export default function SearchBox() { const [query, setQuery] = useState(""); const debouncedQuery = useDebouncedValue(query, 500); useEffect(() => { if (debouncedQuery.length >= 3) { console.log("Search:", debouncedQuery); } }, [debouncedQuery]); return ( <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Type to searchโฆ" /> ); } โ
Fires only after 500ms of inactivity
โ
Perfect for live search or filtering
โก Debounce Callbacks with Control
import { useDebouncedCallback } from "@er-raj-aryan/use-smart-debounce"; function ResizeTracker() { const debouncedResize = useDebouncedCallback( () => console.log("Window resized:", window.innerWidth), 300, { leading: false, trailing: true } ); useEffect(() => { window.addEventListener("resize", debouncedResize); return () => window.removeEventListener("resize", debouncedResize); }, []); return <p>Resize the window to see it in action</p>; } ๐ช Async-Safe Debouncing
This is where most debounce hooks fail โ multiple async calls return out of order, and the old response overwrites the new one.
useDebouncedAsync handles that for you:
import { useDebouncedAsync } from "@er-raj-aryan/use-smart-debounce"; import { useState, useEffect } from "react"; function LiveSearch() { const [query, setQuery] = useState(""); const { run, status, data, error } = useDebouncedAsync( async (q: string) => { if (q.length < 3) return []; const res = await fetch(`/api/search?q=${encodeURIComponent(q)}`); const json = await res.json(); return json.results ?? []; }, 500 ); useEffect(() => { run(query); }, [query]); return ( <div> <input value={query} onChange={(e) => setQuery(e.target.value)} /> {status === "loading" && <p>Loadingโฆ</p>} {error && <p style={{ color: "red" }}>Error fetching</p>} <ul> {Array.isArray(data) && data.map((r: any) => <li key={r.id}>{r.name}</li>)} </ul> </div> ); } โจ Features:
- Cancels the previous API call when user keeps typing
- Prevents stale results from overwriting fresh ones
- Tracks
status,data, anderror
๐งฎ Real Example โ HS Code Lookup with Material UI
Hereโs a practical example using MUIโs <Autocomplete> with your HS Code API (/db/hs_code_list/?search_key=):
import { Autocomplete, TextField } from "@mui/material"; import { useDebouncedAsync } from "@er-raj-aryan/use-smart-debounce"; import { useState, useEffect } from "react"; type HS = { hs_code: string; description: string }; export default function HSCodeSearch() { const [value, setValue] = useState<HS | null>(null); const [options, setOptions] = useState<HS[]>([]); const { run, status, data } = useDebouncedAsync( async (q: string) => { if (q.length < 3 || !/^\d+$/.test(q)) return []; const res = await fetch(`/db/hs_code_list/?search_key=${q}`); const json = await res.json(); return json.results ?? []; }, 600 ); useEffect(() => { if (Array.isArray(data)) setOptions(data); }, [data]); return ( <Autocomplete size="small" options={options} value={value} onChange={(_, v) => setValue(v)} getOptionLabel={(o) => o.hs_code} onInputChange={(_, v) => run(v)} renderInput={(params) => ( <TextField {...params} label="HS Code" helperText={ value?.description || (status === "loading" ? "Searching..." : "") } /> )} /> ); } โ๏ธ Comparison Table
| Feature | @er-raj-aryan/use-smart-debounce | use-debounce | ahooks | lodash.debounce |
|---|---|---|---|---|
| ๐ง TypeScript support | โ Native | โ | โ | โ |
| โ๏ธ Async-safe | โ Cancels + ignores stale | โ | โ ๏ธ Partial | โ |
| ๐ Leading/Trailing | โ | โ ๏ธ Partial | โ | โ |
| ๐ Race protection | โ Yes | โ | โ | โ |
| โก Bundle size | <3 KB | ~4 KB | ~200 KB | 24 KB |
| ๐งฉ Dependencies | 0 | 0 | 20+ | 1 |
| ๐งฐ Designed for React | โ Hooks | โ Hooks | โ | โ |
๐ Why Youโll Love It
- No dependencies โ ultra-fast build
- Tiny footprint โ great for production apps
- Async-safe โ ideal for API-driven UIs
- TypeScript-ready โ works out of the box
๐ Wrap Up
If youโre building React apps that rely on API queries, form inputs, or live filters โ
@er-raj-aryan/use-smart-debounce will save you time, requests, and user frustration.
๐ Install now:
npm i @er-raj-aryan/use-smart-debounce ๐ Links:
๐งโ๐ป Author: Er Raj Aryan
Frontend Engineer | React / Next.js Developer | Open Source Enthusiast
If you found this useful โ โญ๏ธ the repo or drop a comment!
Letโs build smarter UIs together ๐
Top comments (0)