Use Copy To Clipboard
Copy to clipboard React hook: a client hook that writes text to the clipboard and reports copied for a set timeout, or failed until the next try. A late earlier write never overrides a newer one.
"use client"
import { useCallback, useEffect, useRef, useState } from "react"
// timeout is the knob: how long `copied` stays true, in ms. `failed` holds
// until the next try, so the fallback instruction never times out. The
// returned promise says whether the write landed.
function useCopyToClipboard({ timeout = 2000 }: { timeout?: number } = {}) {
const [copied, setCopied] = useState(false)
const [failed, setFailed] = useState(false)
const timer = useRef<ReturnType<typeof setTimeout> | null>(null)
// Each try gets a number; only the latest one sets the feedback or the
// timer, so an earlier write finishing late never overrides a newer one.
const attempt = useRef(0)
useEffect(
() => () => {
if (timer.current) clearTimeout(timer.current)
},
[]
)
const copyToClipboard = useCallback(
async (text: string) => {
const current = ++attempt.current
let ok = true
try {
await navigator.clipboard.writeText(text)
} catch {
ok = false
}
if (current !== attempt.current) return ok
if (timer.current) clearTimeout(timer.current)
setCopied(ok)
setFailed(!ok)
timer.current = setTimeout(() => setCopied(false), timeout)
return ok
},
[timeout]
)
return { copied, failed, copyToClipboard }
}
export { useCopyToClipboard }
"use client"
import { useCopyToClipboard } from "@/hooks/use-copy-to-clipboard"
import { Button } from "@/components/ui/button"
// Every word on the page. Change copy here, not in the markup.
const COPY = {
body: "Make something worth keeping.",
cta: "Copy text",
status: "Copied",
status2: "Ready to copy",
} as const
export default function CopyDemo() {
const { copied, copyToClipboard } = useCopyToClipboard()
return (
<div data-demo="use-copy-to-clipboard" className="flex flex-col gap-6">
<code>{COPY.body}</code>
<Button onClick={() => copyToClipboard(COPY.body)}>{COPY.cta}</Button>
<p role="status">{copied ? COPY.status : COPY.status2}</p>
</div>
)
}
Installation
pnpm dlx shadcn@latest add @01orbital/use-copy-to-clipboardnpx shadcn@latest add @01orbital/use-copy-to-clipboardyarn dlx shadcn@latest add @01orbital/use-copy-to-clipboardbunx --bun shadcn@latest add @01orbital/use-copy-to-clipboardUsed in blocks
2 blocks are built with Use Copy To Clipboard:
Last updated on