useCopyToClipboard
Copies text to the clipboard.
Installation
Props
Prop | Type | Default | Description |
---|---|---|---|
duration | number | 1500 | The duration of the copied state |
Data
Prop | Type | Description |
---|---|---|
copied | boolean | Whether the text has been copied |
copy | function | The function to copy the text to the clipboard |
Key Features & Details
Browser Support & Fallback
- Uses the modern
navigator.clipboard.writeText
API if available. - Falls back to a legacy method using a hidden textarea and
document.execCommand('copy')
for older browsers.
Error Handling
- If copying fails, the hook logs an error and returns
false
from thecopy
function.
Copied State & Duration
- The
copied
state is set totrue
when copying succeeds, and automatically resets tofalse
after the specifiedduration
(in ms).
Cleanup
- Any pending timeout is cleared when the component unmounts, preventing memory leaks or unexpected state changes.
Best Practices & Caveats
- The hook is client-side only; on the server, it does not interact with the clipboard.
- Some browsers may block clipboard access unless triggered by a user gesture (e.g., a button click).
- The fallback method may not work in all environments (e.g., some mobile browsers).
- For best performance, avoid creating new
copy
functions on every render.
Examples
Basic Usage
const { copied, copy } = useCopyToClipboard();
<button onClick={() => copy('Hello!')}>{copied ? 'Copied!' : 'Copy'}</button>;
Custom Duration
const { copied, copy } = useCopyToClipboard(3000);
Handling Copy Result
const { copy } = useCopyToClipboard();
const handleCopy = async () => {
const success = await copy('Some text');
if (success) alert('Copied!');
};