API Reference
useDebounce

useDebounce

This hook is designed to debounce updates to a given value. Debouncing is a technique used to delay the execution of a function or, in this case, the update of a value until a specified period of inactivity has passed. This is particularly useful when dealing with user input or API calls to avoid excessive and rapid updates.

Usage

  1. Make sure you have @ridgehkr/useful installed in your application. If not, you can get started by following the installation instructions.

  2. Import useDebounce into your component.

import { useDebounce } from '@ridgehkr/useful'

Example

The hook returns the debounced version of the value argument:

const debouncedValue = useDebounce(value, delay)

In your React component:

DebouncedInput.jsx
import { useState } from 'react'
import { useDebounce } from '@ridgehkr/useful'
 
function DebouncedInput() {
  const [inputValue, setInputValue] = useState('')
  const debouncedInputValue = useDebounce(inputValue, 500)
 
  const handleInputChange = (e) => {
    setInputValue(e.target.value)
  }
 
  return (
    <div>
      <input
        type='text'
        placeholder='Type something...'
        onChange={handleInputChange}
      />
      <p>Debounced Value: {debouncedInputValue}</p>
    </div>
  )
}

In this example, the inputValue state is being debounced with a delay of 500 milliseconds. The displayed "Debounced Value" will only update once the user has stopped typing for 500 milliseconds.

API Reference

Hook Signature

useDebounce(value: T, delay: number): T

Parameters

useDebounce accepts two parameters:

PropertyTypeRequiredDescription
valueTyesThe value to debounce.
delaynumberyesThe debounce delay in milliseconds.

Return Value

PropertyTypeDescription
debouncedValueTThe debounced version of the input value.

A Note on Debouncing

Keep in mind that debouncing may introduce a slight delay in reflecting the most recent value, which can be a desired behavior in some scenarios but not in others. Make sure to choose an appropriate delay value based on your application's requirements.