Docs
useCopyToClipboard

Copy text to the clipboard easily with useCopyToClipboard, while keeping track of the most recently copied value.

Installation

pnpm dlx shadcn@latest add https://hookcn.ouassim.tech/r/use-copy-to-clipboard

Usage

import { useCopyToClipboard } from "@/hooks/use-copy-to-clipboard"
 
export function Component() {
  const [copiedText, copy] = useCopyToClipboard()
 
  const handleCopy = (text: string) => () => {
    copy(text)
      .then(() => {
        console.log("Copied!", { text })
      })
      .catch((error) => {
        console.error("Failed to copy!", error)
      })
  }
 
  return (
    <>
      <h1>Click to copy:</h1>
      <div style={{ display: "flex" }}>
        <button onClick={handleCopy("A")}>A</button>
        <button onClick={handleCopy("B")}>B</button>
        <button onClick={handleCopy("C")}>C</button>
      </div>
      <p>Copied value: {copiedText ?? "Nothing is copied yet!"}</p>
    </>
  )
}

API Reference

Returns

The useCopyToClipboard hook returns a tuple with the following elements:

IndexTypeDescription
0string | nullThe copied text as string or null if nothing has been copied yet.
1(text: string) => Promise<boolean>Function to copy text to the clipboard.