Skip to Content
HooksuseCopyToClipboard

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

Idle

This is a real UI pattern: one input, one copy button, short-lived success feedback, and a reset path for repeated actions.

Nothing copied yet.

Import

import { useCopyToClipboard } from "react-rsc-kit/client";

Signature

const { copied, copiedText, error, status, isSupported, copy, reset } = useCopyToClipboard(options?);

Parameters

NameTypeDefaultDescription
resetTimenumber | null1500How long copied stays true before resetting. Use null to keep the success state until reset().
onSuccess(copiedText: string) => voidundefinedRuns after a successful copy.
onError(error: Error) => voidundefinedRuns when copy fails.
disableFallbackbooleanfalseDisables the execCommand("copy") fallback and requires the Clipboard API.

Returns

KeyTypeDescription
copiedbooleanWhether the last copy succeeded and is still in its success window.
copiedTextstring | nullLast successfully copied text.
errorError | nullLast copy error, if one exists.
status"idle" | "success" | "error"Current copy state.
isSupportedbooleanWhether copy support exists in the current environment.
copy(text: string) => Promise<void>Copies text to the clipboard.
reset() => voidClears 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.writeText first and falls back to document.execCommand("copy") when allowed.
  • Clipboard support can vary by browser context, permissions, and secure-origin requirements.
  • Use resetTime: null when you want success state to persist until the user dismisses it.
  • For richer UI feedback, combine copied, status, and error with your own toast or alert system.
Last updated on