1.5 KiB
1.5 KiB
useCopyToClipboard
Copies a string to the clipboard and exposes a temporary isCopied flag that resets after a configurable timeout.
Signature
function useCopyToClipboard(options?: { timeout?: number; onCopy?: () => void }): {
isCopied: boolean;
copyToClipboard: (value: string) => void;
};
Options
| Option | Type | Default | Description |
|---|---|---|---|
timeout |
number |
2000 |
Milliseconds before isCopied resets to false |
onCopy |
() => void |
— | Callback fired immediately after a successful copy |
Returns
| Property | Type | Description |
|---|---|---|
isCopied |
boolean |
true for timeout ms after each copy |
copyToClipboard |
(value: string) => void |
Writes value to the clipboard |
Usage
function CopyButton({ code }: { code: string }) {
const { isCopied, copyToClipboard } = useCopyToClipboard({ timeout: 1500 });
return <button onClick={() => copyToClipboard(code)}>{isCopied ? 'Copied!' : 'Copy'}</button>;
}
Notes
- Uses the
navigator.clipboardAPI — no-ops silently in non-secure contexts or environments without clipboard support. - Client-only (
'use client'). Does not run during SSR.