Wake Lock
Keep the screen on while it matters — cook mode for recipes, timers, boarding passes — with the Screen Wake Lock API.
Example
Phones dim and lock after 30 seconds to a few minutes without a touch. That breaks any page people read without touching it: a recipe while their hands are covered in flour, a workout timer, sheet music, a QR code at a gate. Recipe sites solve it with a "Cook mode" switch that keeps the screen on.
- Whisk 2 eggs with 200 ml milk.
- Add 120 g flour and a pinch of salt; whisk until smooth.
- Rest the batter for 10 minutes.
- Heat a buttered pan over medium heat.
- Pour a thin layer, cook 1 minute per side.
On a desktop the screen-sleep part is hard to observe, but the status log
still shows the lifecycle: turn cook mode on, switch to another tab, come
back — the status goes waiting while the tab is hidden, then pending and
held again. Open the page on a phone to see the screen actually stay on.
Install with the shadcn CLI, or copy the source below.
npx shadcn@latest add https://ui-patterns.stereobooster.com/r/use-wake-lock.json"use client";
import * as React from "react";
export type WakeLockStatus =
| "unknown"
| "unsupported"
| "idle"
| "pending"
| "waiting"
| "held"
| "error";
const subscribeNever = () => () => {};
/**
* Keeps the screen awake while `active` is `true` and the page is visible.
* The browser drops the lock whenever the page is hidden (status `waiting`);
* the hook re-acquires it when the page becomes visible again, and
* immediately if the browser drops it while the page is still visible.
*
* `unknown` is returned during server rendering and hydration, before
* support can be detected.
*/
export function useWakeLock(active: boolean): {
status: WakeLockStatus;
error: Error | null;
} {
const supported = React.useSyncExternalStore(
subscribeNever,
() => "wakeLock" in navigator,
() => null,
);
const [state, setState] = React.useState<{
status: "pending" | "waiting" | "held" | "error";
error: Error | null;
}>({ status: "pending", error: null });
const [prevActive, setPrevActive] = React.useState(active);
if (active !== prevActive) {
setPrevActive(active);
setState({ status: "pending", error: null });
}
React.useEffect(() => {
if (!active || !supported) return;
let sentinel: WakeLockSentinel | null = null;
let requesting = false;
let disposed = false;
const acquire = async () => {
if (sentinel || requesting) return;
if (document.visibilityState !== "visible") {
setState({ status: "waiting", error: null });
return;
}
requesting = true;
setState({ status: "pending", error: null });
try {
const lock = await navigator.wakeLock.request("screen");
if (disposed) {
void lock.release();
return;
}
sentinel = lock;
lock.addEventListener("release", () => {
sentinel = null;
if (!disposed) void acquire();
});
setState({ status: "held", error: null });
} catch (error) {
if (!disposed) {
setState({
status: "error",
error: error instanceof Error ? error : new Error(String(error)),
});
}
} finally {
requesting = false;
}
};
const onVisibilityChange = () => {
if (document.visibilityState === "visible") void acquire();
};
void acquire();
document.addEventListener("visibilitychange", onVisibilityChange);
return () => {
disposed = true;
document.removeEventListener("visibilitychange", onVisibilityChange);
void sentinel?.release();
};
}, [active, supported]);
if (supported === null) return { status: "unknown", error: null };
if (!supported) return { status: "unsupported", error: null };
if (!active) return { status: "idle", error: null };
return state;
}Usage:
const [cookMode, setCookMode] = useState(false);
const { status } = useWakeLock(cookMode);
// status: "held" → show "Screen will stay on"Notes:
- The browser releases the lock whenever the page is hidden —
switching tabs, minimising, locking the phone. It is never restored
automatically. While hidden the hook reports
waiting; it listens tovisibilitychangeand requests a new lock when the page is visible again andactiveis stilltrue. Forgetting this is the most common wake-lock bug: cook mode silently stops working after the user checks a message. - The browser can also drop the lock while the page is visible — the
spec lets it release at any time. The hook requests a new lock straight
away from the
releaseevent; if the browser won't grant one (say, battery saver just turned on), the request is refused and the status ends aterrorinstead of looping. - The request can be refused — battery-saver mode, a browser policy, an
iframe without permission.
request()rejects with aNotAllowedError; the hook surfaces it asstatus: "error". Only tell the user "Screen will stay on" once the status isheld, not when they flip the switch. - Make it opt-in. Holding the screen on drains the battery. Use an explicit toggle, never acquire on page load, and turn it off when the task ends (last recipe step, timer finished, user leaves the page). The effect cleanup releases the lock on unmount.
- Disable or hide the toggle when unsupported. The hook returns
unsupportedwhennavigator.wakeLockis missing, andunknownduring server rendering — support is detected withuseSyncExternalStore, so the server and the first client render agree and there's no hydration mismatch. - Requirements. Secure context (HTTPS or
localhost) only. Inside an iframe, the embedding page must allow it:<iframe allow="screen-wake-lock">. - Races are handled. If
activeflips off while a request is still in flight, the lock that arrives afterwards is released immediately, and avisibilitychangeduring a pending request doesn't start a second one. - Screen only.
"screen"is the only lock type. A proposal for a CPU-only "system" lock (keep running with the screen off) was dropped. - Before this API the workaround was a hidden, muted, looping video (e.g. NoSleep.js) — browsers don't sleep during video playback. It still works as a fallback for old browsers, at the cost of battery and an extra media element.
Further reading
- MDN — Screen Wake Lock API — reference and browser support.
- Chrome for Developers — Stay awake with the Screen Wake Lock API — use cases and the visibility re-acquire pattern.
- W3C — Screen Wake Lock spec