typescriptintermediate
useScreenWakeLock Hook
Prevents the screen from turning off using the Screen Wake Lock API.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { useState, useCallback, useEffect, useRef } from 'react';
export function useScreenWakeLock() {
const [isActive, setIsActive] = useState(false);
const wakeLockRef = useRef<WakeLockSentinel | null>(null);
const request = useCallback(async () => {
try {
wakeLockRef.current = await navigator.wakeLock.request('screen');
setIsActive(true);
wakeLockRef.current.onrelease = () => setIsActive(false);
} catch {
setIsActive(false);
}
}, []);
const release = useCallback(async () => {
await wakeLockRef.current?.release();
wakeLockRef.current = null;
setIsActive(false);
}, []);
useEffect(() => {
const reacquire = () => {
if (wakeLockRef.current !== null && document.visibilityState === 'visible') {
request();
}
};
document.addEventListener('visibilitychange', reacquire);
return () => document.removeEventListener('visibilitychange', reacquire);
}, [request]);
return { isActive, request, release };
}Use Cases
- Video playback
- Navigation apps
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptintermediate
usePermission Hook
Queries and tracks browser permission state for features like notifications, camera, and geolocation.
Best for: Permission-gated features
#hooks#permissions
typescriptintermediate
useGeolocation Hook
Accesses browser geolocation API with loading, error states, and watch mode support.
Best for: Location-based features
#hooks#geolocation
typescriptbeginner
usePageVisibility Hook
Detects when the page is hidden or visible using the Page Visibility API.
Best for: Pausing animations
#hooks#visibility
typescriptintermediate
useFullscreen Hook
Toggle fullscreen mode on an element using the Fullscreen API with state tracking.
Best for: Video players
#hooks#fullscreen