Shadcn Hooks

useTimeout

A hook that creates a timeout.

Loading...

Installation

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

Copy and paste the following code into your project.

use-memoized-fn.ts
import { useMemo, useRef } from 'react'

type noop = (this: any, ...args: any[]) => any

type PickFunction<T extends noop> = (
  this: ThisParameterType<T>,
  ...args: Parameters<T>
) => ReturnType<T>

export function useMemoizedFn<T extends noop>(fn: T) {
  const fnRef = useRef<T>(fn)

  // why not write `fnRef.current = fn`?
  // https://github.com/alibaba/hooks/issues/728
  fnRef.current = useMemo<T>(() => fn, [fn])

  const memoizedFn = useRef<PickFunction<T>>(undefined)

  if (!memoizedFn.current) {
    memoizedFn.current = function (this, ...args) {
      return fnRef.current.apply(this, args)
    }
  }

  return memoizedFn.current
}

use-timeout.ts
import { useCallback, useEffect, useRef } from 'react'
import { useMemoizedFn } from '@/registry/hooks/use-memoized-fn'

export function useTimeout(fn: () => void, delay: number = 0) {
  const fnRef = useMemoizedFn(fn)
  const timerRef = useRef<number | null>(null)

  const clear = useCallback(() => {
    if (timerRef.current) {
      clearTimeout(timerRef.current)
      timerRef.current = null
    }
  }, [])

  useEffect(() => {
    if (delay < 0) return

    timerRef.current = window.setTimeout(fnRef, delay)

    return () => {
      clear()
    }
  }, [delay])

  return clear
}

API

/**
 * A hook that creates a timeout.
 * @param fn - The function to execute after the timeout
 * @param delay - The delay in milliseconds before the function is executed
 * @returns A function to clear the timeout
 */
export function useTimeout(fn: () => void, delay: number = 0): () => void

Credits

Last updated on