useClipboard
Copy text to clipboard with feedback on success.
useClipboard
A React hook to copy text to the clipboard and track whether the copy was successful using a copied
state.
📦 Installation
No external dependency needed
🧠 Purpose
useClipboard
provides a simple API to trigger clipboard copy operations and optionally show feedback like "Copied!" messages.
💡 Use Cases
- Copy-to-clipboard buttons
- Invite/share links
- Quick code snippet sharing
- Toast notifications on success
📁 Hook Code
import { useState } from "react";
export function useClipboard(): {
copy: (text: string) => void;
copied: boolean;
} {
const [copied, setCopied] = useState(false);
const copy = (text: string) => {
navigator.clipboard.writeText(text).then(() => {
setCopied(true);
setTimeout(() => setCopied(false), 1500);
});
};
return { copy, copied };
}
import { useState } from "react";
export function useClipboard() {
const [copied, setCopied] = useState(false);
const copy = (text) => {
navigator.clipboard.writeText(text).then(() => {
setCopied(true);
setTimeout(() => setCopied(false), 1500);
});
};
return { copy, copied };
}
🧪 Example
import { useClipboard } from "@/hooks/useClipboard";
export default function CopyExample() {
const { copy, copied } = useClipboard();
return (
<div>
<button onClick={() => copy("Hello, world!")}>
{copied ? "Copied!" : "Copy Text"}
</button>
</div>
);
}
🧩 Hook Signature
function useClipboard(): {
copy: (text: string) => void;
copied: boolean;
};
📝 Parameters
No Initial Parameters
This hook has no parameters.
🎯 Returns
Prop | Type | Default |
---|---|---|
copied | boolean | - |
copy | (text: string) => void | - |
🧯 Copy Status
Copied Flag
The copied
value is true for 1.5 seconds after a successful copy.
🏁 Summary
- ✅ Modern clipboard API
- ✅ Visual feedback support
- ✅ Useful for share/copy interactions
🙋 Contribution
Found a bug or improvement? Submit a PR on GitHub