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 is not public on npm yet. Until the first release, pack @diffgazer/add from the repository and install that tarball into this app, which is what puts dgadd on pnpm exec.

UI components require Tailwind CSS v4. Local copy mode imports src/styles/styles.css; package mode uses @diffgazer/ui CSS once packages are available.

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) => voidCalled after a successful write.
options.onError(error: unknown) => voidCalled 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.
copiedrequiredbooleanTrue while status is copied.
failedrequiredbooleanTrue 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.