Skip to content

useCopy

useCopy is the hook under every copy button. It copies text, HTML, images, JSON or several formats at once, and gives you a status to render, a typed error when it fails, and retry and reset.

Hover a row, or Tab to it and press Enter. Then paste anywhere.
Email shubh@example.com
ID PLT-29018
Rich HTML INV-29018, web design, ₹12,400
JSON { "id": "CUS-77", "active": true }
PNG image
Failure path Fails on purpose, to show an honest error.

State tape: real versus shown

  1. Each copy logs how long it really took, and which states you were shown.

One component per row

Text, rich HTML with a plain-text fallback, JSON and PNG images share one state machine. The failure row shows what users see when something really breaks.

<CopyField.Root value="shubh@example.com" label="Email">
  <CopyField.Label />
  <CopyField.Value />
  <CopyField.Trigger />
</CopyField.Root>
import { useCopy } from "react-smart-copy";
function InvoiceNumber({ id }: { id: string }) {
const { copy, status, error } = useCopy({ resetAfterMs: 1500 });
return (
<button type="button" onClick={() => void copy(id)} data-state={status}>
{status === "copied" ? "Copied" : "Copy"}
{error && <span role="alert">{error.type}</span>}
</button>
);
}

copy() never rejects. It resolves to a CopyOutcome you can branch on:

const outcome = await copy(id);
if (outcome.status === "error") track("copy_failed", outcome.error.type);

Copy what the server makes after the click

Section titled “Copy what the server makes after the click”

A share link, an invite token, a signed URL: often the text only exists once the server has answered. Pass an async function. It receives the copy’s AbortSignal, so a cancelled copy also cancels the request:

const { copy, status } = useCopy();
<button type="button" onClick={() => void copy(async ({ signal }) => {
const response = await fetch(`/api/share/${docId}`, { method: "POST", signal });
return (await response.json()).url;
})}>
{status === "copying" ? "Creating link…" : status === "copied" ? "Link copied" : "Copy share link"}
</button>;

Browsers only let a page write the clipboard during the user’s click, and Safari ends that moment at the first await. The library starts the write during the click with a promise of the text, so it works in Safari too; Chromium and Firefox keep the click valid for several seconds. Checked in all three engines with a half-second server.

  • The source may resolve to text or JSON (copied as text). Build HTML before the click; for pictures, give an image payload an async blob.
  • While the server answers, status is copying and state.payload is null; the copied payload is known once the text arrives.
  • A rejected request is an invalid-payload error whose cause is what was thrown (a CopyFailure keeps its own type). A second click while waiting is ignored, reset() or unmounting cancels the request through the signal, and text that arrives after that is never written.
  • If the write itself fails after the text arrived, retry() writes the same text again without asking the server.
useCopy({
resetAfterMs: 2000, // false or Infinity keeps "copied" until the next action
maxRetries: 3,
onCopy: (payload) => {}, // inline functions are fine; the latest one is always used
onError: (error, payload) => {},
onReset: () => {}, // reset() left a non-idle state (not the automatic reset)
onCancel: (reason) => {}, // "reset" | "disconnect": a copy in flight was cancelled
adapter: myAdapter, // swap the clipboard backend (tests, Electron, native bridges)
coordinator: null, // opt out of the surrounding <CopyGroup>
});

Every copy and paste gets an AbortSignal. It fires when the operation is superseded, when you call reset(), or when the component unmounts. The state machine already ignores late results; the signal lets the work stop too, so a slow screenshot or a large clipboard decode doesn’t keep running (and holding memory) after nobody needs it.

  • Image sources receive it: copy({ kind: "image", blob: (context) => render(context?.signal) })
  • captureSource / captureImage wire it up for you, combined with any signal you pass
  • Custom adapters receive it as their last argument: write(payload, { signal }), read(options, { signal })

The signal never fires after an operation has finished. If a cancelled operation fails anyway, the promise you awaited resolves { status: "ignored", reason: "cancelled" } rather than an error, and onError is not called, so you never toast a failure for work the user walked away from. Adapters and sources written before 1.2 keep working: the argument is optional.

To observe cancellations (for analytics, or to clean up your own work), pass onCancel. It receives why the operation stopped: "reset", "disconnect" (the component unmounted) or, for paste only, "superseded" (a paste event replaced a Clipboard API read). It fires once per cancelled operation and never for one the library has already settled, so React Strict Mode’s extra mount/unmount does not trigger it. (If the clipboard resolves in the same tick as the cancellation, the awaited promise may still report the result; state is not updated.) When reset() cancels work, onCancel("reset") runs first, then onReset().

usePaste({
onCancel: (reason) => analytics.track("paste_cancelled", { reason }),
onReset: () => setDraft(""),
});