useClipboard
Copy text to a user’s clipboard
useClipboard provides a simple interface for reading and writing to the system clipboard using the Clipboard API. It returns a tuple of the most recently copied text, a copy function, and whether the Clipboard API is supported. When the Clipboard API is unavailable, copying falls back to document.execCommand("copy"), while copy and cut events read the current text selection.
When to Use
- Adding “copy to clipboard” buttons for code snippets, URLs, or share links
- Building a paste-from-clipboard feature in forms or editors
- Implementing copy functionality in data tables or dashboards
Notes
- SSR-safe: Returns an empty string, a copy function, and
falseduring server-side rendering. Nonavigatoraccess occurs on the server. - Browser support:
isSupportedreports whethernavigator.clipboardis available. Copying still falls back todocument.execCommand("copy")in browsers without the Clipboard API. - Permissions: Some browsers require user permission for Clipboard API access. Use alongside
usePermissionto checkclipboard-readandclipboard-writestatus.
Usage
Live Editor
function Demo() { const [value, setValue] = useState(""); const [text, copy, isSupported] = useClipboard(); const permissionRead = usePermission("clipboard-read"); const permissionWrite = usePermission("clipboard-write"); return ( <div> <p> Clipboard Permission: read <b>{permissionRead}</b> | write <b>{permissionWrite}</b> </p> <p> Clipboard API supported: <b>{isSupported ? "yes" : "no"}</b> </p> <p> Current copied: <code>{text || "none"}</code> </p> <input value={value} onChange={(event) => { setValue(event.currentTarget.value); }} /> <button onClick={() => copy(value)}>Copy</button> </div> ); };
Result
API
useClipBoard
Returns
readonly [string, (txt: string) => Promise<void>, boolean]: Returns a readonly tuple containing the clipboard text, copy function, and support status.