# usePermission

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

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

## Usage

```ts
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>
```

## 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

```ts
function usePermission(name: PermissionName | (string & {})): PermissionValue
```

| Parameter | Description |
| --- | --- |
| `name` | A permission name, e.g. `'geolocation'`, `'notifications'`, `'camera'`, `'microphone'`, `'clipboard-read'`. |

### Types

```ts
export type PermissionValue = PermissionState | "unknown";
```

## Browser support

Works in all modern browsers.

- Browsers support different permission names; a name the browser doesn't know reports `'unknown'`.

---

319 B minified and brotlied
Source: https://github.com/vincentri/react-tils/blob/main/src/usePermission.ts
Docs page: https://vincentri.github.io/react-tils/hooks/usePermission/
Previous: [usePreferredLanguages](https://vincentri.github.io/react-tils/hooks/usePreferredLanguages.md)
Next: [useGeolocation](https://vincentri.github.io/react-tils/hooks/useGeolocation.md)
