Skip to content
Protocore Design Systemv1.6.9

/// 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

useCopyToClipboard
function useCopyToClipboard(timeout?: number): {
  copied: boolean;
  copy: (value: string) => Promise<boolean>;
  error: Error | null;
};

Parameters

ParameterTypeDescription
timeoutnumberMilliseconds the copied flag stays true before resetting. Default 2000.

Returns

FieldTypeDescription
copiedbooleanTrue for `timeout` ms after a successful copy, then false.
copy(value: string) => Promise<boolean>Copies the string; resolves to whether it succeeded.
errorError | nullThe 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 error to fall back.

Example

a copy button
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.