Shadcn Hooks

useDebounce

A hook to debounce a value

Loading...

Installation

npx shadcn@latest add @hooks/use-debounce
pnpm dlx shadcn@latest add @hooks/use-debounce
yarn dlx shadcn@latest add @hooks/use-debounce
bun x shadcn@latest add @hooks/use-debounce

Copy and paste the following code into your project.

use-debounce-fn.ts
import { debounce } from 'es-toolkit'
import { useMemo } from 'react'
import { useLatest } from '@/registry/hooks/use-latest'
import { useUnmount } from '@/registry/hooks/use-unmount'
import type { DebounceOptions } from 'es-toolkit'

export type { DebounceOptions }

export function useDebounceFn<Fn extends (...args: any[]) => any>(
  fn: Fn,
  debounceMs?: number,
  options?: DebounceOptions,
) {
  const fnRef = useLatest(fn)

  const debouncedFn = useMemo(
    () =>
      debounce(
        (...args: Parameters<Fn>) => fnRef.current(...args),
        debounceMs ?? 1000,
        options,
      ),
    [],
  )

  useUnmount(() => debouncedFn.cancel())

  return {
    run: debouncedFn,
    cancel: debouncedFn.cancel,
    flush: debouncedFn.flush,
  }
}

use-debounce.ts
import { useEffect, useState } from 'react'
import { useDebounceFn } from '@/registry/hooks/use-debounce-fn'
import type { DebounceOptions } from '@/registry/hooks/use-debounce-fn'

export function useDebounce<T>(
  value: T,
  debounceMs?: number,
  options?: DebounceOptions,
) {
  const [debouncedValue, setDebouncedValue] = useState<T>(value)

  const { run } = useDebounceFn(
    () => {
      setDebouncedValue(value)
    },
    debounceMs,
    options,
  )

  useEffect(() => {
    return run()
  }, [value, run])

  return debouncedValue
}

API

interface DebounceOptions {
  /**
   * An optional AbortSignal to cancel the debounced function.
   */
  signal?: AbortSignal
  /**
   * An optional array specifying whether the function should be invoked on the leading edge, trailing edge, or both.
   * If `edges` includes "leading", the function will be invoked at the start of the delay period.
   * If `edges` includes "trailing", the function will be invoked at the end of the delay period.
   * If both "leading" and "trailing" are included, the function will be invoked at both the start and end of the delay period.
   * @default ["trailing"]
   */
  edges?: Array<'leading' | 'trailing'>
}

/**
 * A hook to debounce a value
 * @param value - The value to debounce
 * @param debounceMs - The debounce time in milliseconds default to 1000
 * @param options - The options for the debounce value
 * @returns The debounced value
 */
export function useDebounce<T>(
  value: T,
  debounceMs?: number,
  options?: DebounceOptions,
): T

Credits

Last updated on