# useCopyToClipboard

Copies text to the clipboard and reports `copied` for a short time, for a "Copied!" label.

`copy` resolves to `true` on success and `false` when the browser refuses (no permission, insecure context, or no Clipboard API). Copying again restarts the timer. The timer is cleared on unmount.

## Import

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

## Usage

```ts
const [copy, copied] = useCopyToClipboard()
return <button onClick={() => copy(apiKey)}>{copied ? 'Copied!' : 'Copy'}</button>
```

## When to use it

A "Copy" button for a code snippet, link, or API key.

## When not to

You need to copy rich content (HTML, images); call `navigator.clipboard.write()` with a `ClipboardItem`. Call `copy` from a user action (click, keypress); browsers block clipboard writes otherwise.

## API

```ts
function useCopyToClipboard(resetMs?: number): [(text: string) => Promise<boolean>, boolean]
```

| Parameter | Description |
| --- | --- |
| `resetMs` | How long `copied` stays `true`. Default `2000`. |

**Returns** `[copy, copied]`.

## Browser support

Works in all modern browsers.

- Needs a secure page (HTTPS or localhost). `copy` resolves to `false` when the browser refuses.

---

177 B minified and brotlied
Source: https://github.com/vincentri/react-tils/blob/main/src/useCopyToClipboard.ts
Docs page: https://vincentri.github.io/react-tils/hooks/useCopyToClipboard/
Previous: [useAnimationFrame](https://vincentri.github.io/react-tils/hooks/useAnimationFrame.md)
Next: [useShare](https://vincentri.github.io/react-tils/hooks/useShare.md)
