Skip to main content

Overview

The useClipboard hook provides a simple interface for copying text to the clipboard using the modern Clipboard API. It automatically manages the copied state with a customizable duration and handles errors gracefully.

Function Signature

const useClipboard = (duration?: number) => {
  copied: boolean
  error: Error | null
  copyToClipboard: (text: string) => Promise<void>
}

Parameters

duration
number
default:2000
The duration in milliseconds that the copied state remains true before automatically resetting to false. Defaults to 2000ms (2 seconds).

Return Values

copied
boolean
A boolean indicating whether text was recently copied successfully. Automatically resets to false after the specified duration.
error
Error | null
An Error object if the copy operation failed, or null if there was no error. Errors are cleared on successful copy operations.
copyToClipboard
(text: string) => Promise<void>
An async function that copies the provided text to the clipboard. It updates the copied and error states based on the operation’s success or failure.

Usage Example

Here’s a real-world example from the BookmarkOptions component (/home/daytona/workspace/source/src/components/BookmarkOptions.tsx:23):
import useClipboard from "../hooks/useClipboard"
import { showInfoToast, showErrorToast } from "../utils/showToast"

const BookmarkOptions = ({ bookmark }) => {
  const { copyToClipboard, error, copied } = useClipboard()

  const copyUrl = (url: string) => {
    copyToClipboard(url)
    if (error) return showErrorToast(error.message)
    showInfoToast("URL copied to clipboard!")
  }

  return (
    <button onClick={() => copyUrl(bookmark.url)}>
      {copied ? <Check width={16} /> : <Copy width={16} />}
      Copy link
    </button>
  )
}

Implementation Details

The hook:
  • Uses the modern navigator.clipboard.writeText() API
  • Sets copied to true and clears any previous errors on successful copy
  • Automatically resets copied to false after the specified duration
  • Captures and stores any errors that occur during the copy operation
  • The copyToClipboard function is memoized with useCallback for stable references

Common Use Cases

  • Copying URLs to share content
  • Copying code snippets from documentation
  • Copying text from read-only fields
  • Implementing “Copy to clipboard” buttons with visual feedback

Browser Compatibility

This hook uses the Clipboard API which requires a secure context (HTTPS). It may not work in older browsers or insecure contexts.

Error Handling

The hook catches all errors and stores them in the error state. Common errors include:
  • Permission denied by the user
  • Clipboard API not available (insecure context)
  • Browser doesn’t support the Clipboard API
const { copyToClipboard, error } = useClipboard()

useEffect(() => {
  if (error) {
    console.error('Clipboard error:', error.message)
  }
}, [error])

Custom Duration Example

// Keep the copied state for 5 seconds
const { copied, copyToClipboard } = useClipboard(5000)

return (
  <button onClick={() => copyToClipboard("Hello World")}>
    {copied ? "Copied!" : "Copy"}
  </button>
)

Build docs developers (and LLMs) love