useCopyToClipboard
useCopyToClipboard copies text, exposes success and error state, and gives you a small resettable feedback loop for copy actions.
Live Example
Copy action
This demo shows a common install-command pattern with short success feedback and manual reset.
Clipboard action
Copy install command
This is a real UI pattern: one input, one copy button, short-lived success feedback, and a reset path for repeated actions.
Import
import { useCopyToClipboard } from "react-rsc-kit/client";Signature
const { copied, copiedText, error, status, isSupported, copy, reset } =
useCopyToClipboard(options?);Parameters
| Name | Type | Default | Description |
|---|---|---|---|
resetTime | number | null | 1500 | How long copied stays true before resetting. Use null to keep the success state until reset(). |
onSuccess | (copiedText: string) => void | undefined | Runs after a successful copy. |
onError | (error: Error) => void | undefined | Runs when copy fails. |
disableFallback | boolean | false | Disables the execCommand("copy") fallback and requires the Clipboard API. |
Returns
| Key | Type | Description |
|---|---|---|
copied | boolean | Whether the last copy succeeded and is still in its success window. |
copiedText | string | null | Last successfully copied text. |
error | Error | null | Last copy error, if one exists. |
status | "idle" | "success" | "error" | Current copy state. |
isSupported | boolean | Whether copy support exists in the current environment. |
copy | (text: string) => Promise<void> | Copies text to the clipboard. |
reset | () => void | Clears success and error state manually. |
Usage
"use client";
import { useCopyToClipboard } from "react-rsc-kit/client";
export function CopyInviteLink() {
const { copied, error, copy } = useCopyToClipboard({
resetTime: 2000,
});
return (
<div>
<button type="button" onClick={() => copy("https://example.com/invite")}>
{copied ? "Copied" : "Copy invite link"}
</button>
{error ? <p>{error.message}</p> : null}
</div>
);
}Notes
- The hook uses
navigator.clipboard.writeTextfirst and falls back todocument.execCommand("copy")when allowed. - Clipboard support can vary by browser context, permissions, and secure-origin requirements.
- Use
resetTime: nullwhen you want success state to persist until the user dismisses it. - For richer UI feedback, combine
copied,status, anderrorwith your own toast or alert system.
Last updated on