A React hook for the Screen Wake Lock API that prevents the device's screen from turning off
npm install use-wake-lock  
This hook uses the native Screen Wake Lock API that was released in Chrome v84. As this is a newly released feature, you may first want to check browser compatibility.
``bash`
npm install --save use-wake-lock
An example page is available here. The source code for the example can be found here.
Checkbox (or similar) that can be toggled to turn wake lock on or off.
`jsx
import React from "react";
import { useWakeLock } from "use-wake-lock";
const Example = () => {
const { toggleWakeLock, wakeLockActive } = useWakeLock();
return (
name="wakelock"
type="checkbox"
checked={wakeLockActive}
onChange={() => toggleWakeLock()}
/>
{wakeLockActive ? "on" : "off"}
);
};
`
Button (or similar) that can be clicked to turn wake lock on. After a set period, provided in milliseconds, the wake lock is released.
`jsx
import React from "react";
import { useWakeLock } from "use-wake-lock";
const Example = () => {
const { toggleWakeLock, wakeLockActive } = useWakeLock();
return (
{wakeLockActive ? " on" : " off"}
);
};
`
The hook provides three values:
- toggleWakeLock: A function you can call to toggle the wake lock. It accepts an optional parameter that is the duration (in milliseconds) that the wake lock should be active for.wakeLockActive
- : A boolean indicating whether the wake lock is active. The default value is false.wakeLockError`: A string containing any errors when using the Wake Lock API. The most common error is if the browser does not support the API. The default value is an empty string.
-
MIT.