All hooks / Page, device, and user

usePermission

319 B minified and brotliedSourceMarkdown✓ Works in all modern browsers

The current state of a browser permission ('granted', 'denied', 'prompt'), updated when the user changes it in browser settings.

Returns 'unknown' on the server, during hydration, while the browser answers (one async query, shared by every component), and when the browser does not support querying that permission. Never triggers a permission prompt.

Import

import { usePermission } from '@vincent.ri/react-tils'
// or only this hook
import { usePermission } from '@vincent.ri/react-tils/usePermission'

Usage

const permission = usePermission('notifications')
if (permission === 'denied') return <p>Notifications are blocked in your browser settings.</p>
if (permission !== 'granted') return <button onClick={() => Notification.requestPermission()}>Enable notifications</button>

Live demo

No prompt until you click.

permission: unknown

When to use it

Deciding whether to show a "Enable notifications" or "Use my location" button, or explaining how to re-enable a denied permission.

When not to

You need to ask for the permission; call the feature's own API from a user action (e.g. Notification.requestPermission(), or useGeolocation). Treat 'unknown' as "might work": support differs a lot between browsers (e.g. Firefox and Safari don't support querying camera).

API

function usePermission(name: PermissionName | (string & {})): PermissionValue
ParameterDescription
nameA permission name, e.g. 'geolocation', 'notifications', 'camera', 'microphone', 'clipboard-read'.

Types

export type PermissionValue = PermissionState | "unknown";

Browser support

UsesChromeEdgeFirefoxSafariChrome AndroidSafari iOS
Permissions APIWidely available43+79+46+16+43+16+
  • Browsers support different permission names; a name the browser doesn't know reports 'unknown'.

First version with support, from MDN's compatibility data (web-features 3.42.0, @mdn/browser-compat-data 8.1.5).