react-copy-clipboard-hook
v1.1.0
Published
A modern, lightweight React hook to copy text to clipboard using the Clipboard API.
Readme
react-copy-clipboard-hook
The modern replacement for react-copy-to-clipboard. A lightweight, hook-based React library to copy text to the clipboard using the native Clipboard API. No component wrappers, no legacy APIs—just a simple useClipboard hook.
If you're migrating from react-copy-to-clipboard, this library gives you the same functionality with a modern, hook-first API, TypeScript support, and better control over success and error states.
Installation
npm install react-copy-clipboard-hookyarn add react-copy-clipboard-hookpnpm add react-copy-clipboard-hookUsage
Basic example
import { useClipboard } from 'react-copy-clipboard-hook';
function CopyButton() {
const { isCopied, copy, isSupported } = useClipboard();
return (
<button
onClick={() => copy('Hello, clipboard!')}
disabled={!isSupported}
>
{isCopied ? 'Copied!' : 'Copy'}
</button>
);
}With options: resetDuration and onError
import { useClipboard } from 'react-copy-clipboard-hook';
function CopyButton() {
const { isCopied, copy, isSupported } = useClipboard({
resetDuration: 3000, // Reset "Copied" state after 3 seconds (default: 2000)
onError: (error) => console.error('Copy failed:', error),
});
const handleCopy = async () => {
const success = await copy('Some text');
if (success) {
// Optional: show toast, analytics, etc.
}
};
return (
<button onClick={handleCopy} disabled={!isSupported}>
{isCopied ? 'Copied!' : 'Copy'}
</button>
);
}Disable auto-reset
Set resetDuration to 0 to keep isCopied true until the next copy attempt or unmount:
const { isCopied, copy } = useClipboard({ resetDuration: 0 });Check clipboard support (SSR / unsupported browsers)
The hook is SSR-safe and exposes isSupported so you can disable UI or show a fallback when the Clipboard API isn't available (e.g. non-HTTPS, older browsers):
const { isCopied, copy, isSupported } = useClipboard();
if (!isSupported) {
return <span>Copy not supported in this browser.</span>;
}
return (
<button onClick={() => copy(text)}>
{isCopied ? 'Copied!' : 'Copy'}
</button>
);Copy dynamic or user input
Pass any string into copy()—from state, props, or refs:
function CopyInput() {
const [value, setValue] = useState('');
const { isCopied, copy, isSupported } = useClipboard();
return (
<div>
<input
value={value}
onChange={(e) => setValue(e.target.value)}
disabled={!isSupported}
/>
<button onClick={() => copy(value)} disabled={!isSupported}>
{isCopied ? 'Copied!' : 'Copy'}
</button>
</div>
);
}Handle errors explicitly
copy(text) returns Promise<boolean>. Use it with onError for logging or user feedback:
const [error, setError] = useState<string | null>(null);
const { isCopied, copy, isSupported } = useClipboard({
onError: (err) => setError(err.message),
});
const handleCopy = async () => {
setError(null);
const ok = await copy(textToCopy);
if (!ok) setError('Copy failed');
};API Reference
useClipboard(options?)
Returns an object with:
| Property | Type | Description |
|-------------|-------------------------------|-------------|
| isCopied | boolean | true after a successful copy until reset (or next copy). |
| copy | (text: string) => Promise<boolean> | Copies text to the clipboard. Resolves true on success, false on failure or unsupported environment. |
| isSupported | boolean | true when the Clipboard API is available (and in a browser). Safe to use for SSR. |
Options
| Option | Type | Default | Description |
|------------------|-------------------------|----------|-------------|
| resetDuration | number | 2000 | Milliseconds after which isCopied is set back to false. Use 0 to disable auto-reset. |
| onError | (error: Error) => void | — | Called when copy fails (unsupported, invalid input, or clipboard error). |
copy(text: string)
- Returns:
Promise<boolean>—trueif the copy succeeded,falseotherwise. - Behavior:
- If the environment doesn't support the Clipboard API, returns
falseand optionally callsonError. - If
textis not a string, returnsfalseand optionally callsonError. - On success, sets
isCopiedtotrueand schedules a reset afterresetDurationms (if > 0). - On clipboard failure (e.g. permission denied), sets
isCopiedtofalse, callsonError, and returnsfalse.
- If the environment doesn't support the Clipboard API, returns
Requirements
- React
>= 16.8.0(hooks support) - Browser: Clipboard API support (HTTPS in production; see browser support)
Why use this instead of react-copy-to-clipboard?
| react-copy-to-clipboard (legacy) | react-copy-clipboard-hook (modern replacement) |
|----------------------------------|-------------------------------------------------|
| Component-based (<CopyToClipboard>) | Hook-based (useClipboard) — fits any UI |
| Uses document.execCommand('copy') | Uses native navigator.clipboard (Clipboard API) |
| Less control over success/error | copy() returns Promise<boolean>, plus onError and isSupported |
| No built-in “copied” state timing | Configurable resetDuration (or disable with 0) |
| — | SSR-safe and TypeScript-friendly |
License
MIT © Sameer Thite
