30% offEnding soon
usePermissionLoading saved progress…

usePermission

The Permissions API lets you inspect whether access to a browser capability is granted, denied, or still waiting for a prompt. Implement a React hook that queries one permission name, exposes a predictable loading and failure model, and stays synchronized with the returned PermissionStatus. Your hook must remain correct when the permission name changes while an earlier query is still pending.

Signature

function usePermission(name: string): {
  state: 'loading' | 'granted' | 'denied' | 'prompt' | 'unsupported';
  error: Error | null;
};

Examples

const { result } = renderHook(() => usePermission('geolocation'));

// Before navigator.permissions.query() resolves:
result.current; // { state: 'loading', error: null }

// After it resolves to a PermissionStatus whose state is "granted":
result.current; // { state: 'granted', error: null }
// In a browser without navigator.permissions.query:
const { result } = renderHook(() => usePermission('camera'));
result.current; // { state: 'unsupported', error: null }

Notes

  • Query exactly — pass { name } to navigator.permissions.query().
  • Track changes — subscribe to the resolved status object's change event and freshly read its state each time.
  • Handle races — ignore query resolutions and rejections that arrive after unmount or after name changes.
  • Clean up — remove the exact listener from the exact status object that was queried.
  • Stay read-only — do not request, revoke, or implement an API-specific permission prompt.