Skip to main content

useLockFn

function useLockFn<A extends unknown[], R>(
fn: (...args: A) => Promise<R>,
): (...args: A) => Promise<R | undefined>;

Wraps an async function so only one call runs at a time, such as a payment button clicked twice. While a call is running, further calls are ignored: they don't call fn and resolve to undefined. Once the call settles, the lock is released whether it succeeded or failed, and a failure is passed on to whoever made the call. The returned function keeps its identity for the component's lifetime and always calls the latest fn.

Live demo​

Click as fast as you like: only one order goes through at a time.

Orders placed: 0

Example​

import { useLockFn } from "react-honey-hooks";

function PayButton({ orderId }: { orderId: string }) {
const pay = useLockFn(async () => {
await api.pay(orderId);
});
return <button onClick={() => void pay()}>Pay</button>;
}