useDebounce

NEW

React hook to delay the execution of function or state update.

Add the hook via the CLI:

npx @novajslabs/cli add useDebounce

Or copy and paste the code into your project:

import { useEffect, useState } from 'react'

export const useDebounce = <T>(value: T, delay: number) => {
  const [debouncedValue, setDebouncedValue] = useState<T>(value)

  useEffect(() => {
    const handleTimeout = setTimeout(() => {
      setDebouncedValue(value)
    }, delay)

    return () => {
      clearTimeout(handleTimeout)
    }
  }, [value, delay])

  return debouncedValue
}

React 16.8 or higher

  • Name
    value
    Type
    any
    Required
    required
    Description

    The value that you want to debounce.

  • Name
    delay
    Type
    number
    Required
    required
    Description

    The delay time in milliseconds. After this time, the latest value is used.

  • Name
    debouncedValue
    Type
    any
    Description

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

import { useState } from 'react'
import { useDebounce } from './hooks/useDebounce'

const fruits = [
  'Apple',
  'Banana',
  'Mango',
  'Grapes',
  'Papaya',
  'Coconut',
  'Guava',
  'Orange',
  'Pineapple',
  'Watermelon',
]

const App = () => {
  const [searchTerm, setSearchTerm] = useState('')
  const debouncedSearchTerm = useDebounce(searchTerm, 500)

  const filteredFruits = fruits.filter((fruit) =>
    fruit.toLowerCase().includes(debouncedSearchTerm.toLowerCase()),
  )

  return (
    <div>
      <input
        type="text"
        placeholder="Search..."
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)}
      />
      <ul>
        {filteredFruits.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
    </div>
  )
}

export default App

Here are some use cases where this React hook is useful:

  • Debouncing a search input to avoid excessive API calls
  • Delaying the execution of a function to wait for user pause in typing
  • Reducing the frequency of state updates in response to user actions
  • Improving performance by limiting the number of renders caused by fast-changing values