DOM
useCopyToClipboard
Copy text to the clipboard, tracking the last copied value.
Demo
live · imported from hookli
Copy, then paste to confirm it worked.
- copiedText
- null
import { useCopyToClipboard } from "hookli";
export function Demo() {
const [copiedText, copy] = useCopyToClipboard();
return (
<button type="button" onClick={() => copy("npm i hookli")}>
{copiedText ? "Copied!" : "Copy"}
</button>
);
}Usage
import { useCopyToClipboard } from "hookli";
export function Demo() {
const [copiedText, copy] = useCopyToClipboard();
return (
<button type="button" onClick={() => copy("npm i hookli")}>
{copiedText ? "Copied!" : "Copy"}
</button>
);
}API
useCopyToClipboard(): [CopiedValue, CopyFn]Parameters
This hook takes no parameters.
Returns
| Name | Type | Description |
|---|---|---|
| [0] copiedText | CopiedValue | The last successfully-copied string, or null before any copy or after a failed one. |
| [1] copy | CopyFn | Writes text to the clipboard. Resolves true on success, false when the API is unavailable or the write is rejected. |
CopiedValue
| Name | Type | Description |
|---|---|---|
| value | string | null | The tracked copied text, or null. |
CopyFn
| Name | Type | Description |
|---|---|---|
| value | (text: string) => Promise<boolean> | Copies text and reports whether the write succeeded. |
Hook
The implementation, straight from hookli. Copy it, or install the package.
import { useCallback, useState } from "react";
type CopiedValue = string | null;
type CopyFn = (text: string) => Promise<boolean>;
type UseCopyToClipboardReturn = [CopiedValue, CopyFn];
export function useCopyToClipboard(): UseCopyToClipboardReturn {
const [copiedText, setCopiedText] = useState<CopiedValue>(null);
const copy: CopyFn = useCallback(async (text) => {
if (typeof navigator === "undefined" || !navigator.clipboard) {
return false;
}
try {
await navigator.clipboard.writeText(text);
setCopiedText(text);
return true;
} catch {
setCopiedText(null);
return false;
}
}, []);
return [copiedText, copy];
}