Loading...
Please waitLoading...
Please waitCoordinate exclusive or shared browser work across tabs with a React wrapper around the Web Locks API.
pnpm dlx uselab@latest add use-web-lock
import { useWebLock } from "@/hooks/use-web-lock"
export function SyncOwner() {
const { isLocked, acquire, release } = useWebLock("background-sync")
return (
<div className="space-y-2">
<button onClick={() => void acquire()} disabled={isLocked}>
Become sync owner
</button>
<button onClick={release} disabled={!isLocked}>
Release ownership
</button>
</div>
)
}useWebLock(name, options?)| Name | Type | Description | Optional |
|---|---|---|---|
name | string | Lock name shared by every tab competing for the same resource. | No |
options | UseWebLockOptions | Lock acquisition behavior and lifecycle callbacks. | Yes |
The hook returns an object { isSupported, isLocked, error, acquire, release }:
| Name | Type | Description |
|---|---|---|
isSupported | boolean | Whether the Web Locks API exists in the current browser. |
isLocked | boolean | Whether this hook instance currently holds the lock. |
error | Error | null | Last lock acquisition error. |
acquire | () => Promise<boolean> | Attempts to acquire the lock and resolves to true when acquired. |
release | () => void | Releases the currently held lock. |
interface UseWebLockOptions {
mode?: "exclusive" | "shared"
ifAvailable?: boolean
steal?: boolean
onAcquire?: (lock: { name: string; mode: "exclusive" | "shared" }) => void
onRelease?: () => void
}mode: Lock mode to request. Defaults to "exclusive".ifAvailable: Return immediately when the lock is not available instead of waiting.steal: Request the lock aggressively when supported by the browser.onAcquire: Runs when the lock is granted.onRelease: Runs when the lock is released.This is useful for cross-tab leader election, background sync ownership, and single-writer browser workflows.