/// hooks
useCopyToClipboard
Copy text to the clipboard and get a transient copied boolean back — the primitive behind copy-on-click Tag, CodeBlock, and Copy-for-LLM. The flag resets itself after a timeout, so a “Copied” affordance needs no manual cleanup.
Signature
function useCopyToClipboard(timeout?: number): {
copied: boolean;
copy: (value: string) => Promise<boolean>;
error: Error | null;
};Parameters
| Parameter | Type | Description |
|---|---|---|
timeout | number | Milliseconds the copied flag stays true before resetting. Default 2000. |
Returns
| Field | Type | Description |
|---|---|---|
copied | boolean | True for `timeout` ms after a successful copy, then false. |
copy | (value: string) => Promise<boolean> | Copies the string; resolves to whether it succeeded. |
error | Error | null | The last copy error, or null. Set when the Clipboard API is unavailable. |
When to use
- Add a copy button to a code snippet, an id, an API key, or a share link.
- Show a brief “Copied” confirmation without wiring your own timer.
- Handle failure gracefully — the clipboard can be blocked by permissions or an insecure context; branch on
errorto fall back.
Example
import { useCopyToClipboard } from "@protocore/pds";
function CopyButton({ value }: { value: string }) {
const { copied, copy } = useCopyToClipboard();
return (
<button type="button" onClick={() => copy(value)}>
{copied ? "Copied" : "Copy"}
</button>
);
}Note
The Clipboard API needs a secure context (HTTPS or
localhost) and, in some browsers, a user gesture. When it is unavailable, copy resolves false and sets error rather than throwing.