Skip to main content

useCopyToClipboard

useCopyToClipboard is a custom React hook that copies text to the clipboard and reports whether the copy succeeded or failed.

Usage

import { useCopyToClipboard } from "hookify-react";

export default function UseCopyToClipboardExample() {
const { copy, isCopied, error } = useCopyToClipboard();

return (
<div style={{ textAlign: "center", fontFamily: "Arial, sans-serif" }}>
<h2>useCopyToClipboard Hook Example</h2>
<button onClick={() => copy("Hello, Clipboard!")}>
Copy to Clipboard
</button>
{isCopied && <p style={{ color: "green" }}>Copied successfully!</p>}
{error && <p style={{ color: "red" }}>Error copying: {error.message}</p>}
</div>
);
}

API Reference

Parameters

ParameterTypeDefaultDescription
resetDelaynumber2000Milliseconds before isCopied resets to false. Pass 0 to disable auto-reset.

Return Value

useCopyToClipboard returns an object with the following properties:

PropertyTypeDescription
copy(text: string) => Promise<boolean>Copies the given text. Resolves to true on success and false on failure.
isCopiedbooleantrue if the last copy succeeded, otherwise false.
errorError | nullThe Error thrown by the last failed copy, or null. Render error.message to display it.

Behavior

  • Uses the modern navigator.clipboard.writeText API when available.
  • Falls back to a document.execCommand("copy") approach for insecure (non-HTTPS) contexts where the async Clipboard API is unavailable.
  • Sets isCopied to true on success and automatically resets it after resetDelay milliseconds (unless resetDelay is 0).
  • Captures the thrown Error (not just a string) in error, and sets isCopied to false on failure.
  • Clears any pending reset timer on unmount to avoid state updates on an unmounted component.