Function: useWebLock()
useWebLock(
name,options?):UseWebLockReturn
Defined in: use-web-lock.ts:125
Runs async work under a named lock from the Web Locks API, so only one
holder at a time (exclusive) or any number of holders together (shared)
can execute it across tabs, windows, and workers of the same origin. Useful
to avoid duplicate token refreshes or concurrent writes to shared storage.
Call run(fn) to wait for the lock, run fn while holding it, and release
it when fn resolves or rejects. isPending and isHeld report whether
a call is waiting for or holding the lock.
Lock requests still waiting when the component unmounts are aborted, and
their run rejects with an AbortError. A lock that is already held is
not taken away: it lasts until fn settles, so use the signal passed
to fn to stop long work on unmount. No state is updated after unmount.
When navigator.locks is missing (server rendering, unsupported browser,
or insecure context), run calls fn(null, signal) directly without any
locking, and isHeld stays false.
Parameters
name
string
The lock name. Holders of the same name in the same origin contend with each other.
options?
Optional default lock settings,
which each run call can override.
Returns
The run function and the isHeld and isPending state.
Examples
const { run, isPending } = useWebLock("token-refresh");
const refresh = () =>
run(async () => {
const token = await fetchNewToken();
saveToken(token);
});
return (
<button onClick={refresh} disabled={isPending}>
Refresh
</button>
);
// Skip the work when another tab is already doing it
const { run } = useWebLock("sync", { ifAvailable: true });
const sync = async () => {
const result = await run((_lock, signal) => syncData({ signal }));
if (result === undefined) console.log("Another tab is syncing");
};
For a live, editable example, see the useWebLock docs page.