useDebounce

Performance

A React hook that delays updating a value until a specified time has passed since the last change, useful for reducing API calls and expensive operations.

Demo

1. Search Input

Debounced:
Type to search. API call will be made 500ms after you stop typing.
Start typing to search

2. Real-time Updates

Value: 50°
Debounced: 50°
Move the slider to change the hue. Color updates 200ms after you stop moving.

Installation

npm install @thibault.sh/hooks

Usage

import { useDebounce } from "@thibault.sh/hooks";

function SearchInput() {
  const [search, setSearch] = useState("");
  const debouncedSearch = useDebounce(search, 500);

  useEffect(() => {
    // API call will only be made 500ms after the user stops typing
    if (debouncedSearch) {
      searchApi(debouncedSearch);
    }
  }, [debouncedSearch]);

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

API Reference

Returns

The debounced value

Parameters

value

The value to debounce. This can be any type of value (string, number, object, etc.). The hook will return a new value of the same type after the delay.

delay

The time in milliseconds to wait before updating the debounced value after the last change. A typical value is 500ms for search inputs or 200ms for other UI updates.

Return Value

Returns the debounced value. The value will only update after the specified delay has passed since the last change to the input value.

Type: T (same type as input value)

Features

Performance Optimization

Reduces the frequency of expensive operations like API calls, DOM updates, or heavy computations by waiting for user input to stabilize.

Type Safety

Full TypeScript support with generics, ensuring type safety between the input value and the debounced output.

Memory Efficient

Properly cleans up timeouts on component unmount and value changes, preventing memory leaks and unnecessary updates.

Flexible Usage

Works with any value type and can be used for various scenarios like search inputs, form validation, or real-time UI updates.