typescriptintermediate

usePermission Hook

Queries and tracks browser permission state for features like notifications, camera, and geolocation.

typescript
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.