Skip to content

Copy to Clipboard

hookclipboardfeedback

Copy-to-clipboard state machine. Writes text to the clipboard and exposes an idle, copied, or failed status that resets after a delay.

tsx
const { status, copy } = useCopyToClipboard({ resetMs: 1500 });return (  <button type="button" onClick={() => copy("var(--foreground)")}>    {status === "copied" ? "Copied" : "Copy"}  </button>);

Installation

$pnpm exec dgadd add ui/copy-to-clipboard
[Installs to]src/hooks/use-copy-to-clipboard.ts[Item]ui/copy-to-clipboard

dgadd ships in @diffgazer/add on npm: pnpm add -D @diffgazer/add puts it on pnpm exec, and npx @diffgazer/add runs it without the install.

UI components require Tailwind CSS v4. Local copy mode imports src/styles/styles.css; package mode uses @diffgazer/ui CSS from the installed package.

Parameters

NameTypeDefaultDescription
options.resetMsnumber2000Milliseconds before copied or failed status resets to idle.
options.write(text: string) => Promise<void> | voidnavigator.clipboard.writeTextCustom clipboard writer. Useful for tests or alternate clipboard adapters.
options.onCopy(text: string) => void—Called after a successful write.
options.onError(error: unknown) => void—Called when the write fails.

Returns

UseCopyToClipboardResultCurrent copy status plus an async copy command.
NameTypeDefaultDescription
statusrequired"idle" | "copied" | "failed"—Current state of the last copy attempt.
copiedrequiredboolean—True while status is copied.
failedrequiredboolean—True while status is failed.
copyrequired(text: string) => Promise<boolean>—Writes text and resolves true on success or false on failure.

Notes

Reset behavior

Each copy attempt restarts the reset timer. The pending timer is cleared when the component unmounts.

Clipboard writer

By default the hook calls navigator.clipboard.writeText. Pass write when your environment needs a custom clipboard implementation.

Source

Highlighted source loads after this disclosure opens. Browse the source repository.