Skip to main content

useWebLock

Run async work under a named lock from the Web Locks API, so only one tab, window or worker at a time (or any number, in shared mode) executes it. Lock requests are cleaned up on unmount.

When to use it​

  • Avoiding duplicate token refreshes when several tabs notice an expired token.
  • Serializing writes to shared storage such as IndexedDB or localStorage.
  • Making sure a sync or migration runs in only one tab (ifAvailable).
  • Letting many readers proceed together while a writer waits (shared).

Demo​

Click Run 2s task on both workers: the second one shows "waiting for the lock..." until the first finishes, and the Console tab logs the order. Open the page in another tab to see the tabs take turns. The last example skips the work when the lock is already held.

Loading demo…

Signature​

interface UseWebLockOptions {
mode?: LockMode; // "exclusive" | "shared"
ifAvailable?: boolean;
steal?: boolean;
}

interface UseWebLockRunOptions extends UseWebLockOptions {
signal?: AbortSignal;
}

type WebLockCallback<T> = (
lock: Lock | null,
signal: AbortSignal
) => T | Promise<T>;

interface UseWebLockReturn {
run: <T>(
fn: WebLockCallback<T>,
options?: UseWebLockRunOptions
) => Promise<T | undefined>;
isHeld: boolean;
isPending: boolean;
}

function useWebLock(
name: string,
options?: UseWebLockOptions
): UseWebLockReturn;
ParameterTypeDescription
namestringThe lock name. Holders of the same name in the same origin contend.
optionsUseWebLockOptionsDefault lock settings for every run call. Each call can override them.
OptionTypeDescription
mode"exclusive" | "shared"One holder at a time, or any number together. Defaults to "exclusive".
ifAvailablebooleanSkip the work if the lock can't be granted right away. run then resolves undefined.
stealbooleanTake the lock immediately, aborting the current holder. Exclusive mode only. Use with care.

run accepts the same options as its second argument, plus signal.

Returns:

PropertyTypeDescription
run<T>(fn, options?) => Promise<T | undefined>Waits for the lock, runs fn while holding it, then releases the lock.
isHeldbooleantrue while fn is running with the lock held.
isPendingbooleantrue while a run call is waiting for the lock.

fn receives (lock, signal):

ArgumentTypeDescription
lockLock | nullThe granted lock, or null when the Web Locks API is unavailable and fn runs without locking.
signalAbortSignalAborts on unmount or when the signal given to run aborts. Pass it to fetch or check it in loops.

Usage notes​

  • The lock is released when fn resolves or rejects. A rejection from fn is passed through to the run caller.
  • run resolves undefined when ifAvailable skips the work. If fn can itself return undefined, return a distinct value (such as true) so you can tell a skip from a result.
  • On unmount, requests still waiting for the lock are aborted and their run rejects with an AbortError. Use the exported isAbortError(error) to tell it from a real failure. A lock that is already held can't be revoked: it is kept until fn settles, so honor the signal passed to fn to stop long work early. State is never updated after unmount.
  • steal makes the previous holder's run reject with an AbortError. The browser doesn't allow steal or ifAvailable together with an abort signal, so the signal you pass to run then only reaches fn, never the lock request. Neither option waits for the lock anyway.
  • Pass a per-call signal to cancel one waiting request without unmounting: run(fn, { signal: controller.signal }).
  • Locks are shared by every tab, window and worker of the same origin. They are not shared across origins, and an exclusive request from the same tab also waits for a lock that tab already holds, so avoid calling run with the same name from inside fn: it would wait on itself forever.
  • When navigator.locks is missing (server rendering, an unsupported browser or an insecure context), run calls fn(null, signal) directly with no locking, and isHeld stays false. Check the lock argument if the work must not run unprotected. The Web Locks API needs a secure context (HTTPS or localhost).
  • isPending and isHeld cover every run call made through the same hook instance, and stay true until the last one finishes. Nothing touches navigator during render, so the hook is SSR-safe.
  • run keeps a stable identity until name changes. The options you pass to the hook are read when run is called, so inline objects are safe.

Example​

const { run, isPending } = useWebLock("token-refresh");

const getToken = () =>
run(async (_lock, signal) => {
// Another tab may have refreshed while we waited for the lock
if (!isExpired(readToken())) return readToken();

const response = await fetch("/api/refresh", { signal });
const { token } = await response.json();
saveToken(token);
return token;
});
// Readers share the lock, a writer takes it alone
const reader = useWebLock("cache", { mode: "shared" });
const writer = useWebLock("cache");

Hook source​

View useWebLock source

use-web-lock.ts
import { useCallback, useEffect, useRef, useState } from "react";

import { useLatest } from "./use-latest";

/** Options for {@link useWebLock}. They map to the options of `navigator.locks.request`. */
export interface UseWebLockOptions {
/**
* `"exclusive"` lets one holder at a time own the lock, `"shared"` lets any
* number of holders own it together. Default is `"exclusive"`.
*/
mode?: LockMode;
/**
* If the lock cannot be granted immediately, skip the work: `fn` is not
* called and `run` resolves `undefined`. Default is `false`.
*/
ifAvailable?: boolean;
/**
* Release any lock with the same name held in this origin and grant this
* request right away. The previous holder's `run` rejects with an
* `AbortError`. Needs `"exclusive"` mode. Default is `false`.
*/
steal?: boolean;
}

/** Per-call options for the `run` function returned by {@link useWebLock}. */
export interface UseWebLockRunOptions extends UseWebLockOptions {
/**
* Aborts the call. While the lock is still being waited for, `run` rejects
* with the signal's reason. Once the lock is held, `fn` receives an
* `AbortSignal` that follows this one. Ignored by the browser, but still
* forwarded to `fn`, when `ifAvailable` or `steal` is set.
*/
signal?: AbortSignal;
}

/**
* The function {@link UseWebLockReturn.run | run} calls while holding the lock.
*
* @param lock - The granted `Lock`, or `null` when the Web Locks API is not
* available and `fn` runs without a lock.
* @param signal - Aborted when the component unmounts or the `signal` passed to
* `run` aborts. Pass it to `fetch` or check it in loops to stop early and free
* the lock sooner.
*/
export type WebLockCallback<T> = (
lock: Lock | null,
signal: AbortSignal
) => T | Promise<T>;

/** Value returned by {@link useWebLock}. */
export interface UseWebLockReturn {
/**
* Waits for the lock, runs `fn` while holding it, and releases the lock once
* `fn` settles, whether it resolves or rejects. Resolves with the value
* `fn` returns, or `undefined` if `ifAvailable` skipped the work. Rejects
* with whatever `fn` throws, or with an `AbortError` if the request was
* aborted (see {@link isAbortError}). It keeps a stable identity until `name`
* changes.
*/
run: <T>(
fn: WebLockCallback<T>,
options?: UseWebLockRunOptions
) => Promise<T | undefined>;
/** `true` while `fn` runs holding the lock from at least one `run` call. */
isHeld: boolean;
/** `true` while at least one `run` call is waiting for the lock to be granted. */
isPending: boolean;
}

/**
* 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`.
*
* @param name - The lock name. Holders of the same name in the same origin
* contend with each other.
* @param options - Optional default {@link UseWebLockOptions | lock} settings,
* which each `run` call can override.
* @returns The `run` function and the `isHeld` and `isPending` state.
*
* @example
* ```tsx
* const { run, isPending } = useWebLock("token-refresh");
*
* const refresh = () =>
* run(async () => {
* const token = await fetchNewToken();
* saveToken(token);
* });
*
* return (
* <button onClick={refresh} disabled={isPending}>
* Refresh
* </button>
* );
* ```
*
* @example
* ```ts
* // 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](https://altalyst-solutions.github.io/hookify/hooks/use-web-lock).
*/
export const useWebLock = (
name: string,
options?: UseWebLockOptions
): UseWebLockReturn => {
const [isHeld, setIsHeld] = useState(false);
const [isPending, setIsPending] = useState(false);

const optionsRef = useLatest(options);
const pendingCountRef = useRef(0);
const heldCountRef = useRef(0);
const controllersRef = useRef(new Set<AbortController>());
const unmountedRef = useRef(false);

const syncState = useCallback(() => {
if (unmountedRef.current) return;
setIsPending(pendingCountRef.current > 0);
setIsHeld(heldCountRef.current > 0);
}, []);

useEffect(() => {
unmountedRef.current = false;
const controllers = controllersRef.current;
return () => {
unmountedRef.current = true;
controllers.forEach((controller) => controller.abort());
controllers.clear();
};
}, []);

const run = useCallback(
async <T>(
fn: WebLockCallback<T>,
runOptions?: UseWebLockRunOptions
): Promise<T | undefined> => {
const { mode, ifAvailable, steal, signal } = {
...optionsRef.current,
...runOptions,
};

const controller = new AbortController();
const locks =
typeof navigator === "undefined" ? undefined : navigator.locks;

if (unmountedRef.current) {
controller.abort();
} else {
controllersRef.current.add(controller);
}

const onCallerAbort = () => controller.abort(signal?.reason);
if (signal?.aborted) {
onCallerAbort();
} else {
signal?.addEventListener("abort", onCallerAbort, { once: true });
}

let waiting = false;
const stopWaiting = () => {
if (!waiting) return;
waiting = false;
pendingCountRef.current--;
syncState();
};

try {
if (!locks) return await fn(null, controller.signal);

if (controller.signal.aborted) throw controller.signal.reason;

// The browser rejects `signal` combined with `ifAvailable` or `steal`,
// and neither of those ever waits, so there is nothing to abort.
const lockOptions: LockOptions = {};
if (mode) lockOptions.mode = mode;
if (ifAvailable) lockOptions.ifAvailable = true;
if (steal) lockOptions.steal = true;
if (!ifAvailable && !steal) lockOptions.signal = controller.signal;

waiting = true;
pendingCountRef.current++;
syncState();

return await locks.request(name, lockOptions, async (lock) => {
stopWaiting();
if (!lock) return undefined;

heldCountRef.current++;
syncState();
try {
return await fn(lock, controller.signal);
} finally {
heldCountRef.current--;
syncState();
}
});
} finally {
stopWaiting();
signal?.removeEventListener("abort", onCallerAbort);
controllersRef.current.delete(controller);
}
},
[name, optionsRef, syncState]
);

return { run, isHeld, isPending };
};