useLockFn
Prevents overlapping async function executions.
Prevents overlapping async function executions.
Import
import { useLockFn } from '@kamod-ch/hooks'Live demo
Basic demo
Prevents overlapping async function executions.
Completed runs: 0
In flight: false
import { useState } from 'preact/hooks'
import { useLockFn } from '@kamod-ch/hooks'
export default function UseLockFnDemo() {
const [runs, setRuns] = useState(0)
const [inFlight, setInFlight] = useState(false)
const locked = useLockFn(async () => {
setInFlight(true)
await new Promise((resolve) => window.setTimeout(resolve, 500))
setRuns((value) => value + 1)
setInFlight(false)
})
return (
<div>
<p><strong>Completed runs:</strong> {runs}</p>
<p><strong>In flight:</strong> {String(inFlight)}</p>
<button type="button" onClick={() => { locked(); locked(); locked() }}>Trigger three concurrent calls</button>
</div>
)
}
API
TypeScript signature
declare function useLockFn<P extends any[] = any[], V = any>(fn: (...args: P) => Promise<V>): (...args: P) => Promise<V>;
export default useLockFn;
/SSR considerations
This hook is safe to import during SSR. If your effect body touches the DOM, keep that work inside the effect callback.
Browser compatibility
Works in any modern browser supported by Preact.