Rooks
HooksPerformance & Optimization

useDebouncedValue

Returns a value that follows its input after a delay, plus an immediate setter.

About

useDebouncedValue keeps a local value and updates it only after the input stops changing for the configured timeout. It can initially return null and also exposes the underlying state setter for an immediate override.

Examples

import { useState } from "react";
import { useDebouncedValue } from "rooks";

export default function DebouncedQuery() {
  const [query, setQuery] = useState("");
  const [settledQuery, setSettledQuery] = useDebouncedValue(query, 400, {
    initializeWithNull: true,
  });

  return (
    <label>
      Query
      <input value={query} onChange={(event) => setQuery(event.target.value)} />
      <span>Settled: {settledQuery ?? "waiting"}</span>
      <button type="button" onClick={() => setSettledQuery(query)}>
        Apply now
      </button>
    </label>
  );
}

Parameters

ArgumentTypeDefaultMeaning
valueTrequiredInput value to follow.
timeoutnumberrequiredDebounce delay in milliseconds.
options.initializeWithNullbooleanfalseStarts at null, then schedules the initial value.

The options and tuple types are not public package exports.

Return value

[debouncedValue, immediatelyUpdateDebouncedValue]. The first item is T, or T | null when initializeWithNull: true. The second is a React state dispatcher, so it accepts a value or functional update.

Behavior and lifecycle

Without null initialization, the first input is returned immediately. With it, the first input is scheduled after mount. Later input changes reset the pending trailing update. The timeout and initialization mode are captured for the mounted hook instance; changing them later does not recreate the underlying debounced function or reinitialize state.

The immediate setter does not cancel a pending debounced input, so that pending update can later replace a manual value. Pending work is cancelled on unmount.

Compatibility and accessibility

No DOM API is required. Server output is the immediate initial value or null, matching the selected option. When debounce delays search results or validation, communicate the pending state and keep error text programmatically associated with its input.

On this page