ilias-use-debounce
v3.1.0
Published
A lightweight React hook for debouncing function calls with cancellation support and state tracking.
Downloads
52
Maintainers
Readme
ilias-use-debounce
A small, type-safe React hook for delaying function calls until a period of inactivity has elapsed. It includes cancellation, immediate execution, and state tracking for pending calls.
Installation
npm install ilias-use-debounceUsage
The hook receives the function and delay as positional arguments. The returned debounce function keeps the parameters of the original function through TypeScript inference.
import { useState } from "react";
import { useDebounce } from "ilias-use-debounce";
function SearchComponent() {
const [searchTerm, setSearchTerm] = useState("");
const performSearch = (query: string) => {
console.log("Searching for:", query);
};
const { debounce: debouncedSearch, cancel: cancelSearch, isDebouncing } = useDebounce(
performSearch,
500,
);
return (
<div>
<input
value={searchTerm}
onChange={(e) => {
setSearchTerm(e.target.value);
debouncedSearch(e.target.value);
}}
placeholder="Search..."
/>
<button onClick={cancelSearch}>Cancel</button>
{isDebouncing && <span>Searching...</span>}
</div>
);
}API
useDebounce<T>(fn: T, delay: number): UseDebounceReturn<T>
The timer starts again whenever debounce is called. Only the most recent call is executed.
Arguments
fn— the synchronous or asynchronous function to delay.delay— the delay in milliseconds. Negative values are treated as0.
Return value
The hook returns an object with four properties:
debounce(...args)— schedules the function with the supplied arguments.cancel()— clears the pending call and setsisDebouncingtofalse.flush()— executes the pending call immediately. It does nothing when there is no pending call.isDebouncing—truewhile a call is waiting to be executed.
Pending timers are cleared automatically when the component using the hook unmounts. Calling debounce again replaces the previous pending call.
For cases where you need the latest typed/pending value available for a controlled input (not just the debounced side effect), keep it in local state alongside debounce, as shown above — useDebounce intentionally doesn't store a value itself. If you need debounced and immediate state from one hook, use useStateDebounce. If you need a value that only updates after the delay (e.g. batching list updates), use useDebouncedState instead.
Migrating from v2
Version 3 changes useDebounce's arguments from a single options object to positional parameters:
// v2
const { debounce, cancel, isDebouncing } = useDebounce({ fn, delay: 500 });
// v3
const { debounce, cancel, isDebouncing } = useDebounce(fn, 500);Migrating from v1
Version 2 changes both the arguments and the return value. The v1 API:
const [debounce, cancel, debouncing] = useDebounce(fn, 500);becomes:
const { debounce, cancel, isDebouncing } = useDebounce({ fn, delay: 500 });useStateDebounce
A state hook that returns both the debounced value and the value updated immediately. Use undebouncedState for controlled inputs and state for work that should only run after the delay.
import { useStateDebounce } from "ilias-use-debounce";
function SearchInput() {
const { state, undebouncedState, setState, isDebouncing } = useStateDebounce("", 500);
return (
<>
<input value={undebouncedState} onChange={(event) => setState(event.target.value)} />
{isDebouncing && <span>Searching...</span>}
<SearchResults query={state} />
</>
);
}useStateDebounce<T, A>(initialValue, delay, collect?)
state— the value committed after the delay.undebouncedState— the value updated immediately bysetState.setState(update)— accepts a value or updater function and restarts the delay timer.cancel()— discards the pending update and restoresundebouncedStatetostate.flush()— commits the pending update immediately.isDebouncing—truewhile an update is waiting to be committed.callback(...args)— event-handler-friendly shortcut, usingcollectwhen provided.
Unlike useDebouncedState, this hook returns an object and exposes both state values.
useDebouncedState
A useState-like hook whose value only updates (and re-renders) after a period of inactivity. Functional updates operate on the pending value, so successive calls accumulate correctly — useful for batching list updates without an intermediate re-render per item.
import { useDebouncedState } from "ilias-use-debounce";
function LiveLog() {
const [entries, setEntries, { flush, isDebouncing }] = useDebouncedState<string[]>([], 300);
const addEntry = (entry: string) => {
setEntries((prev) => [...prev, entry]);
};
return (
<div>
<button onClick={() => addEntry(`event ${entries.length}`)}>Add</button>
<button onClick={flush}>Flush now</button>
{isDebouncing && <span>Pending...</span>}
<ul>
{entries.map((entry, index) => (
<li key={index}>{entry}</li>
))}
</ul>
</div>
);
}useDebouncedState<T, A>(initialValue: T | (() => T), delay: number, collect?: (prev: T, ...args: A) => T): [T, (update: T | ((prev: T) => T)) => void, controls]
initialValue— the initial value, or an initializer function (same asuseState).delay— the delay in milliseconds. Negative values are treated as0.collect— optional reducer used bycontrols.callbackto fold incoming arguments into the pending value.
Returns a tuple:
state— the last committed value.setState(update)— accepts a value or an updater function; each call resets the delay timer. Updater functions receive the current pending value, not the last committed one.controls.cancel()— clears the pending update and discards it,isDebouncingbecomesfalse.controls.flush()— commits the pending update immediately. Does nothing when there is no pending update.controls.isDebouncing—truewhile an update is waiting to be committed.controls.callback(...args)— an event-handler-friendly shortcut. It callssetStateunder the hood, usingcollectto merge the arguments into the pending value (or the first argument directly whencollectisn't provided).
Collecting native form validation errors
An HTML form fires one invalid event per invalid field, all in the same tick. callback combined with collect lets you accumulate every ValidityState and update your error state only once, after the last one fires:
import { useDebouncedState } from "ilias-use-debounce";
function ValidatedForm() {
const [invalidFields, , { callback: onInvalid, isDebouncing }] = useDebouncedState<ValidityState[]>(
[],
0,
(prev, event: React.FormEvent<HTMLInputElement>) => [...prev, event.currentTarget.validity],
);
return (
<form onInvalid={onInvalid} noValidate={false}>
<input name="email" type="email" required />
<input name="age" type="number" min={18} required />
<button type="submit">Submit</button>
{isDebouncing && <span>Validating...</span>}
{invalidFields.length > 0 && <pre>{JSON.stringify(invalidFields, null, 2)}</pre>}
</form>
);
}Because onInvalid doesn't bubble natively, React relies on capture-phase delegation to call the handler for every invalid input — callback collects all of them before the debounced commit updates invalidFields once.
Typical uses
- Search inputs and autocomplete requests
- Form validation
- Auto-save behavior
- Resize and scroll handlers
Characteristics
- TypeScript parameter inference
- Support for synchronous and asynchronous functions
- Explicit cancellation and immediate execution
- Automatic timer cleanup on unmount
- React as the only runtime dependency
Development
Install the dependencies and run the test suite:
npm install
npm testCreate a production build with:
npm run buildContributing
See CONTRIBUTING.md for branch and commit conventions. Contributions are expected to include tests when they change behavior.
License
This project is licensed under the ISC License.
