Overview
TheuseClipboard 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
Parameters
The duration in milliseconds that the
copied state remains true before automatically resetting to false. Defaults to 2000ms (2 seconds).Return Values
A boolean indicating whether text was recently copied successfully. Automatically resets to
false after the specified duration.An Error object if the copy operation failed, or
null if there was no error. Errors are cleared on successful copy operations.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):Implementation Details
The hook:- Uses the modern
navigator.clipboard.writeText()API - Sets
copiedtotrueand clears any previous errors on successful copy - Automatically resets
copiedtofalseafter the specified duration - Captures and stores any errors that occur during the copy operation
- The
copyToClipboardfunction is memoized withuseCallbackfor 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 theerror state. Common errors include:
- Permission denied by the user
- Clipboard API not available (insecure context)
- Browser doesn’t support the Clipboard API