use-copy-clipboard-react
v1.0.0
Published
Production-ready React 18 & 19 hook to copy text to clipboard with timeout auto-reset and legacy browser fallback.
Maintainers
Readme
📋 use-copy-clipboard-react
Production-ready, zero-dependency React 18 & 19 hook to copy text to clipboard with automatic reset timers, status feedback, and legacy browser fallback.
✨ Features
- ⏱️ Automatic Feedback Timer —
isCopiedautomatically toggles totrueon copy and resets tofalseafter a configurable duration (default: 2000ms). - 🛡️ Universal Compatibility Fallback — Tries modern
navigator.clipboard.writeTextfirst; seamlessly falls back to hiddendocument.execCommand('copy')on non-HTTPS origins or legacy webviews. - 🧹 Unmount & Leak Safe — Automatically cleans up pending reset timeouts when the component unmounts.
- ⚡ Zero Dependencies — Ultra-lightweight (< 1 KB minified).
- 🧰 Standalone Utility Included — Exports pure async
copyToClipboard(text)function for use outside of React component lifecycles. - 📦 Dual ESM & CommonJS — Works out-of-the-box in Next.js (App & Pages Router), Vite, Remix, Gatsby, and React Native Web.
📥 Installation
# npm
npm install use-copy-clipboard-react
# pnpm
pnpm add use-copy-clipboard-react
# yarn
yarn add use-copy-clipboard-react
# bun
bun add use-copy-clipboard-react🚀 Usage & Real-World Examples
1. Basic Copy Button
import React from 'react';
import { useClipboard } from 'use-copy-clipboard-react';
export function ShareLink({ url }: { url: string }) {
const { copy, isCopied } = useClipboard({ timeoutMs: 2500 });
return (
<div className="flex items-center gap-2">
<input readOnly value={url} className="border p-2 rounded" />
<button
onClick={() => copy(url)}
className="px-4 py-2 bg-blue-600 text-white rounded font-medium"
>
{isCopied ? 'Copied! 🎉' : 'Copy Link'}
</button>
</div>
);
}2. Code Block with Notification Callbacks
import React from 'react';
import { useClipboard } from 'use-copy-clipboard-react';
export function CodeSnippet({ code }: { code: string }) {
const { copy, isCopied, error } = useClipboard({
timeoutMs: 2000,
onSuccess: (text) => console.log('Successfully copied:', text),
onError: (err) => console.error('Failed to copy snippet:', err),
});
return (
<div className="relative code-card">
<button
onClick={() => copy(code)}
className="absolute top-2 right-2 px-2 py-1 bg-gray-800 text-xs text-white rounded"
>
{isCopied ? '✔ Copied' : 'Copy'}
</button>
<pre>
<code>{code}</code>
</pre>
{error && <p className="text-red-500 text-xs">Error: {error.message}</p>}
</div>
);
}3. Using Standalone copyToClipboard() in Event Handlers
If you want to copy text inside an async API handler without creating React state:
import { copyToClipboard } from 'use-copy-clipboard-react';
async function handleGenerateShareToken() {
const token = await generateApiToken();
const success = await copyToClipboard(token);
if (success) {
alert('Token generated and copied to clipboard!');
} else {
prompt('Could not copy automatically. Please copy manually:', token);
}
}📖 API Reference
useClipboard(options?)
Custom hook providing reactive clipboard state and actions.
Options (UseClipboardOptions):
| Option | Type | Default | Description |
|---|---|---|---|
| timeoutMs | number | 2000 | Duration before isCopied resets back to false |
| onSuccess | (text: string) => void | undefined | Callback invoked immediately upon successful copy |
| onError | (error: Error) => void | undefined | Callback invoked if clipboard access fails |
Return Value:
| Property | Type | Description |
|---|---|---|
| copy | (text: string) => Promise<boolean> | Asynchronously copies text to clipboard |
| isCopied | boolean | true while the success feedback timer is active |
| error | Error \| null | Error object if the last copy attempt failed |
| reset | () => void | Clears active timeout and resets state immediately |
copyToClipboard(text)
Pure asynchronous helper function to copy a string to system clipboard.
- Parameters:
text(string): The text to copy.
- Returns:
Promise<boolean>(trueif successful,falseotherwise).
💖 Support the Project
If use-copy-clipboard-react made sharing in your web apps smooth and reliable, please consider sponsoring:
👉 Sponsor @Piratha97 on GitHub Sponsors
📄 License
MIT © 2026 Pirapaakaran Pirathapan
