Skip to content
CannonReactHooks

useDebounce

A custom hook that debounces a value in React.

Play

Debounced value:

Parameters

ParameterTypeDescription
valueanyThe value to be debounced.
delaynumberThe delay in milliseconds before updating the debounced value.
optionsobject, optionalAdditional options for controlling the debounce behavior.
options.headingboolean, default: falseDetermines whether to use the initial heading value.
options.trailingboolean, default: trueDetermines whether to use the trailing value after the delay.

Returns

  • valueToDebounce (any): The debounced value.

Example

import { useState } from "react";
import { useDebounce } from "@cannonui/reacthooks";

const TestUseDebounce = () => {
  const [inputValue, setInputValue] = useState("");
  const debouncedValue = useDebounce(inputValue, 1000);

  const handleChange = (e) => {
    setInputValue(e.target.value);
  };

  return (
    <div>
      <input type="text" value={inputValue} onChange={handleChange} />
      <p>Debounced value: {debouncedValue}</p>
    </div>
  );
};

export default TestUseDebounce;

In the above example, the useDebounce hook is used to debounce the inputValue state. It accepts three parameters: value, delay, and options. The value parameter represents the value to be debounced, the delay parameter specifies the delay in milliseconds before updating the debounced value, and the options parameter allows you to customize the debounce behavior with heading and trailing options.

The hook returns the valueToDebounce, which represents the debounced value.

To use the useDebounce hook, import it from @cannonui/reacthooks and pass the required parameters. In the example component TestUseDebounce, an input field is rendered, and the inputValue state is updated in the handleChange function. The debounced value is displayed below the input field.