useCopyToClipboard
useCopyToClipboard is a custom React hook that copies text to the clipboard and reports whether the copy succeeded or failed.
Usage
import { useCopyToClipboard } from "hookify-react";
export default function UseCopyToClipboardExample() {
const { copy, isCopied, error } = useCopyToClipboard();
return (
<div style={{ textAlign: "center", fontFamily: "Arial, sans-serif" }}>
<h2>useCopyToClipboard Hook Example</h2>
<button onClick={() => copy("Hello, Clipboard!")}>
Copy to Clipboard
</button>
{isCopied && <p style={{ color: "green" }}>Copied successfully!</p>}
{error && <p style={{ color: "red" }}>Error copying: {error.message}</p>}
</div>
);
}
API Reference
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
resetDelay | number | 2000 | Milliseconds before isCopied resets to false. Pass 0 to disable auto-reset. |
Return Value
useCopyToClipboard returns an object with the following properties:
| Property | Type | Description |
|---|---|---|
copy | (text: string) => Promise<boolean> | Copies the given text. Resolves to true on success and false on failure. |
isCopied | boolean | true if the last copy succeeded, otherwise false. |
error | Error | null | The Error thrown by the last failed copy, or null. Render error.message to display it. |
Behavior
- Uses the modern
navigator.clipboard.writeTextAPI when available. - Falls back to a
document.execCommand("copy")approach for insecure (non-HTTPS) contexts where the async Clipboard API is unavailable. - Sets
isCopiedtotrueon success and automatically resets it afterresetDelaymilliseconds (unlessresetDelayis0). - Captures the thrown
Error(not just a string) inerror, and setsisCopiedtofalseon failure. - Clears any pending reset timer on unmount to avoid state updates on an unmounted component.