useCopyToClipboard copies text and tells you it worked. The copied flag resets on a timer, and over plain http or in old browsers the hook falls back to a hidden textarea. It shows no toasts by itself, so you decide how to confirm.
Preview
copied: false
Installation
Usage
import { Button } from "@/components/ui/button"
import { useCopyToClipboard } from "@/hooks/use-copy-to-clipboard"
export function CopyLink({ url }: { url: string }) {
const { copy, copied } = useCopyToClipboard()
return (
<Button type="button" onClick={() => copy(url)}>
{copied ? "Copied" : "Copy link"}
</Button>
)
}Examples
With a toast
Use onCopy and onError to show your own notification. The hook stays silent otherwise.
import { toast } from "@/components/ui/toast"
const { copy } = useCopyToClipboard({
onCopy: () => toast.success("Copied to clipboard"),
onError: () => toast.error("Could not copy"),
})Many items, one hook
copiedText holds the last copied string, so a list can mark exactly the item that was copied.
Palette
import { Button } from "@/components/ui/button"
const { copy, copiedText } = useCopyToClipboard({ timeout: 1500 })
{colors.map((hex) => (
<Button key={hex} type="button" onClick={() => copy(hex)}>
{copiedText === hex ? "Copied" : hex}
</Button>
))}Parameters
| Name | Type | Default | Description |
|---|---|---|---|
| timeout | number | 2000 | How long copied stays true, in ms. 0 keeps it until the next copy |
| onCopy | (text: string) => void | - | Called after a successful copy |
| onError | (error: Error) => void | - | Called when both the Clipboard API and the fallback fail |
Returns
| Name | Type | Description |
|---|---|---|
| copy | (text: string) => Promise<boolean> | Copies the text. Resolves to true on success |
| copied | boolean | true right after a successful copy |
| copiedText | string | null | The last copied string while copied is true |
| error | Error | null | The last error, cleared by the next successful copy |
| reset | () => void | Clears the state and the timer |
Features
- Fallback. Without a secure context or navigator.clipboard it copies through a hidden textarea and puts focus and selection back.
- No side effects. No toasts or styles inside. The hook only reports what happened.
- Clean timers. A new copy restarts the reset timer, and unmounting clears it.