Skip to main content

useDebounce()

Delays updating the parameters by debouncing.

Useful to avoid spamming network requests when parameters might change quickly (like a typeahead field).

To fetch at once and abort the previous fetch, use useCancelling().

React 18+

When loading new data, the AsyncBoundary will continue rendering the previous data until it is ready. isPending will be true while loading.

Usage​

import React from 'react';
import { AsyncBoundary, useDebounce } from '@data-client/react';
import IssueList from './IssueList';

export default function SearchIssues() {
  const [query, setQuery] = React.useState('');
  const [debouncedQuery, isPending] = useDebounce(query, 200);
  const input = React.useRef<HTMLInputElement>(null);
  return (
    <>
      <header className="appHeader">
        <h1 className="appTitle">Issues</h1>
      </header>
      <label className="search" aria-busy={isPending}>
        <input
          ref={input}
          type="search"
          aria-label="Search issues"
          placeholder="Search issues"
          value={query}
          onChange={e => setQuery(e.currentTarget.value)}
        />
        <button
          type="button"
          className="clear"
          aria-label="Clear search"
          onClick={() => {
            setQuery('');
            input.current?.focus();
          }}
        />
      </label>
      <AsyncBoundary fallback={<Loading />} errorComponent={ErrorMessage}>
        <IssueList search={debouncedQuery} stale={query !== debouncedQuery} />
      </AsyncBoundary>
    </>
  );
}
render(<SearchIssues />);
Live Preview

Types​

function useDebounce<T>(
value: T,
delay: number,
updatable?: boolean,
): [T, boolean];

Returns [debouncedValue, isPending]. When updatable is false, the debounced value does not update.