typescriptintermediate
usePermission Hook
Queries and tracks browser permission state for features like notifications, camera, and geolocation.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { useState, useEffect } from 'react';
type PermissionName = 'geolocation' | 'notifications' | 'camera' | 'microphone';
export function usePermission(name: PermissionName) {
const [state, setState] = useState<PermissionState>('prompt');
useEffect(() => {
let mounted = true;
navigator.permissions
.query({ name: name as globalThis.PermissionName })
.then((status) => {
if (!mounted) return;
setState(status.state);
status.onchange = () => {
if (mounted) setState(status.state);
};
})
.catch(() => {
if (mounted) setState('prompt');
});
return () => { mounted = false; };
}, [name]);
return state;
}Use Cases
- Permission-gated features
- Notification opt-in flows
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
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
useScreenWakeLock Hook
Prevents the screen from turning off using the Screen Wake Lock API.
Best for: Video playback
#hooks#wake-lock
typescriptintermediate
useFullscreen Hook
Toggle fullscreen mode on an element using the Fullscreen API with state tracking.
Best for: Video players
#hooks#fullscreen