Docs
Debounce

Debounce

Delay the execution of function or state update.

About

The useDebounce hook helps delay the execution of functions or state updates until a specified time period has passed without any further input changes. This is particularly useful for managing user input or initiating network requests, as it minimizes unnecessary computations and ensures that resource-heavy tasks only run after the input activity has paused.

Parameters

NameTypeDescription
valueanyThe value that you want to debounce. This can be of any type.
delaynumberThe delay time in milliseconds. After this amount of time, the latest value is used.

Return Values

NameTypeDescription
debouncedValueanyThe debounced value. After the delay time has passed without the value changing, this will be updated to the latest value.

Installation

Run the following command:

npx scriptkavi-hooks@latest add debounce

Usage

import { useDebounce } from "@/hooks/debounce"
export default function App() {
  const [searchTerm, setSearchTerm] = React.useState("js")
  const debouncedSearchTerm = useDebounce(searchTerm, 300)
 
  const handleChange = (e) => {
    setSearchTerm(e.target.value)
  }
 
  React.useEffect(() => {
    const callApi = async () => {
      if (debouncedSearchTerm) {
        // Call Api
      }
    }
    callApi()
  }, [debouncedSearchTerm])
 
  return (
    <form>
      <input
        name="search"
        placeholder="Search something..."
        onChange={handleChange}
      />
    </form>
  )
}