useCopyToClipboard

A React hook to robustly copy text to the clipboard with status feedback.

Overview

useCopyToClipboard provides an easy-to-use interface for the modern Browser Clipboard API. It manages the copy state, allowing you to easily provide visual feedback to users (like morphing icons or toast notifications) when a copy operation is successful.

Demo

Copy to Clipboard

Minimalist clipboard utility with elegant feedback.

pnpm add @antigravity/hooks
npm install react-hooks-ts
sk_test_51Mz...

API Reference

function useCopyToClipboard(): [
  string | null, 
  (text: string) => Promise<boolean>
]

Returns

NameTypeDescription
copiedValuestring | nullThe last value that was successfully copied
copy(text: string) => Promise<boolean>Function to copy text to clipboard. Returns true if successful.

Usage Examples

Simple Copy Button

import { useCopyToClipboard } from 'react-hooks-ts'
 
function CopyButton({ text }) {
  const [copiedText, copy] = useCopyToClipboard()
 
  return (
    <button onClick={() => copy(text)}>
      {copiedText ? 'Copied!' : 'Copy to Clipboard'}
    </button>
  )
}

Features

  • Modern API - Uses navigator.clipboard for the best browser support
  • Async Support - Returns a Promise to handle success/failure states
  • 🧩 Status Tracking - Tracks the last copied value for state management
  • 🛡️ Error Handling - Gracefully handles permission issues and lack of browser support
  • 🎨 Flexible UI - Perfect for building morphing buttons and notification toasts