Rooks
Performance & Optimization

useDebounce

Debounces a callback so it only executes after a delay since the last call.

About

Debounce hook for react. Internally, it uses lodash debounce.

Examples

Debounce a text input

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

export default function App() {
  const [value, setValue] = useState("");
  const setValueDebounced = useDebounce(setValue, 500);

  return (
    <div>
      <input
        onChange={(e) => setValueDebounced(e.target.value)}
        placeholder="Please type here"
      />
      <div>{value}</div>
    </div>
  );
}

Trigger immediately on the leading edge

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

export default function LeadingSearch() {
  const [logs, setLogs] = useState([]);
  const logSearch = useDebounce(
    (value) => {
      setLogs((current) => [...current, `search:${value}`]);
    },
    500,
    { leading: true }
  );

  return (
    <div>
      <button onClick={() => logSearch("react hooks")}>Run search</button>
      <pre>{JSON.stringify(logs, null, 2)}</pre>
    </div>
  );
}

Arguments

ArgumentTypeDescriptionDefault value
callbackFunctionThe function to debounceundefined
waitnumberThe duration to debounce in millisecondsundefined
optionsObjectoptions to pass into lodash's debounce

Return Value

NameTypeDescription
debouncedFunctionFunctionThe debounced function

On this page