h3/use's logo

h3/use

Command Palette

Search for a command to run...

useDebounceCallback

Debounce the call of a function.

useDebounceCallback
This component uses the useDebounceCallback hook to debounce the callback function to control the input value.

Imediate value:

Debounced value:

Installation

Props

PropTypeDefaultDescription
delaynumber500The delay in milliseconds before the function is executed.
callbackgeneric TundefinedThe function to be executed after the delay.

Key Features & Details

Callback & Delay Handling

  • The hook always uses the latest version of the callback, even if it changes between renders.
  • The delay can be changed dynamically; the new delay will be used for subsequent calls.

Returned Debounced Function

  • The returned function accepts the same arguments as the original callback.
  • If called repeatedly, only the last call within the delay period will trigger the callback.
  • The debounced function is stable (does not change identity unless delay changes).

Cleanup

  • Any pending timeout is cleared when the component unmounts, preventing memory leaks or unexpected calls.

Best Practices & Caveats

  • The hook is client-side only.
  • For best performance, memoize the callback if it depends on other values.
  • If you need to cancel a pending debounce manually, you must manage that outside the hook.
  • The hook does not guarantee the callback will run if the component unmounts before the delay.

Examples

Basic Usage

const debouncedLog = useDebounceCallback((val) => {
  console.log('Debounced:', val);
}, 300);
 
debouncedLog('hello');

With Changing Delay

const [delay, setDelay] = useState(500);
const debouncedSave = useDebounceCallback(saveFn, delay);

With Dynamic Callback

const debounced = useDebounceCallback((...args) => {
  // Do something with args
}, 200);