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

ilias-use-debounce

v3.1.0

Published

A lightweight React hook for debouncing function calls with cancellation support and state tracking.

Downloads

52

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-debounce

Usage

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 as 0.

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 sets isDebouncing to false.
  • flush() — executes the pending call immediately. It does nothing when there is no pending call.
  • isDebouncing — true while 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 by setState.
  • setState(update) — accepts a value or updater function and restarts the delay timer.
  • cancel() — discards the pending update and restores undebouncedState to state.
  • flush() — commits the pending update immediately.
  • isDebouncing — true while an update is waiting to be committed.
  • callback(...args) — event-handler-friendly shortcut, using collect when 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 as useState).
  • delay — the delay in milliseconds. Negative values are treated as 0.
  • collect — optional reducer used by controls.callback to 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, isDebouncing becomes false.
  • controls.flush() — commits the pending update immediately. Does nothing when there is no pending update.
  • controls.isDebouncing — true while an update is waiting to be committed.
  • controls.callback(...args) — an event-handler-friendly shortcut. It calls setState under the hood, using collect to merge the arguments into the pending value (or the first argument directly when collect isn'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 test

Create a production build with:

npm run build

Contributing

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.