Shadcn Hooks

useLockFn

A hook to lock a function

useLockFn

npx shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-lock-fn.json"
pnpm dlx shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-lock-fn.json"
yarn dlx shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-lock-fn.json"
bun x shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-lock-fn.json"

Copy and paste the following code into your project.

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],
  )
}

Last updated on

On this page