GooseUI

Components

useCopyToClipboard

New

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

npx shadcn@latest add @gooseui/use-copy-to-clipboard
pnpm dlx shadcn@latest add @gooseui/use-copy-to-clipboard
yarn dlx shadcn@latest add @gooseui/use-copy-to-clipboard
bunx --bun shadcn@latest add @gooseui/use-copy-to-clipboard

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

NameTypeDefaultDescription
timeoutnumber2000How 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

NameTypeDescription
copy(text: string) => Promise<boolean>Copies the text. Resolves to true on success
copiedbooleantrue right after a successful copy
copiedTextstring | nullThe last copied string while copied is true
errorError | nullThe last error, cleared by the next successful copy
reset() => voidClears 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.