Skip to content

此页面的翻译正在准备中,暂时显示英文原文。

useDebouncedCallback

useDebouncedCallback is a React hook that returns a debounced version of the provided callback function. It helps optimize event handling by delaying function execution and grouping multiple calls into one. Note that if both 'leading' and 'trailing' are set, the function will be called at both the start and end of the delay period. However, it must be called at least twice within debounceMs interval for this to happen, since one debounced function call cannot trigger the function twice.

Interface

ts
function useDebouncedCallback<T>(options: Object): (nextValue: T) => void;

Parameters

  • optionsrequired · Object

    The options object.

    • options.onChangerequired · (newValue: T) => void

      The callback to debounce. A call with the same value as the last forwarded one is skipped.

    • options.timeThresholdrequired · number

      The number of milliseconds to delay the function execution.

    • options.leadingboolean · false

      If true, the function is called at the start of the sequence.

    • options.trailingboolean · true

      If true, the function is called at the end of the sequence.

Return Value

  • (nextValue: T) => void

    debounced function that forwards the value to onChange.

Example

tsx
import { useDebouncedCallback } from 'react-simplikit';
import { useState } from 'react';

function SearchInput() {
  const [query, setQuery] = useState('');
  const setQueryDebounced = useDebouncedCallback({
    onChange: setQuery,
    timeThreshold: 300,
  });

  return (
    <>
      <input onChange={e => setQueryDebounced(e.target.value)} />
      <p>Searching for: {query}</p>
    </>
  );
}

基于 MIT 许可证发布。