use-lock-fn

PreviousNext

A hook to lock a function until the previous promise is resolved

Docs
hookshook

Preview

Loading preview…
registry/hooks/use-lock-fn.ts
import { useCallback, useRef } from 'react'

export function useLockFn<P extends any[] = any[], V = any>(
  fn: (...args: P) => Promise<V>,
) {
  const lockRef = useRef(false)

  return useCallback(
    async (...args: P) => {
      if (lockRef.current) {
        return
      }

      lockRef.current = true

      try {
        return await fn(...args)
      } finally {
        lockRef.current = false
      }
    },
    [fn],
  )
}

Installation

npx shadcn@latest add @hooks/use-lock-fn

Usage

import { UseLockFn } from "@/hooks/use-lock-fn"
const value = UseLockFn()