Shadcn Hooks

useThrottle

A hook to throttle a value

Loading...

Installation

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

Copy and paste the following code into your project.

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

export type { ThrottleOptions }

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

  const throttledFn = useMemo(
    () =>
      throttle(
        (...args: Parameters<Fn>) => fnRef.current(...args),
        throttleMs ?? 1000,
        options,
      ),
    [],
  )

  useUnmount(() => throttledFn.cancel())

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

use-throttle.ts
import { useEffect, useState } from 'react'
import { useThrottleFn } from '@/registry/hooks/use-throttle-fn'
import type { ThrottleOptions } from '@/registry/hooks/use-throttle-fn'

export function useThrottle<T>(
  value: T,
  throttleMs?: number,
  options?: ThrottleOptions,
) {
  const [throttledValue, setThrottledValue] = useState<T>(value)

  const { run } = useThrottleFn(
    () => {
      setThrottledValue(value)
    },
    throttleMs,
    options,
  )

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

  return throttledValue
}

API

interface ThrottleOptions {
  /**
   * An optional AbortSignal to cancel the throttled 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 ["leading", "trailing"]
   */
  edges?: Array<'leading' | 'trailing'>
}

/**
 * A hook to throttle a value
 * @param value - The value to throttle
 * @param throttleMs - The throttle time in milliseconds default to 1000
 * @param options - The options for the throttle value
 * @returns The throttled value
 */
function useThrottle<T>(
  value: T,
  throttleMs?: number,
  options?: ThrottleOptions,
): T

Credits

Last updated on