Appearance
useClipboard
Reactive Clipboard API. Provides the ability to respond to clipboard commands (cut, copy, and paste) as well as to asynchronously read from and write to the system clipboard. Access to the contents of the clipboard is gated behind the Permissions API. Without user permission, reading or altering the clipboard contents is not permitted.
Demo
Usage
tsx
import { useClipboard } from '@reause/core'
const [text, copy, { copied, isSupported }] = useClipboard({ source: 'Hello' })
copy('Hello') // writes to the clipboard; `copied` auto-resets after 1.5sPass React state directly — the hook always reads the latest value, so reactive sources need no wrapper:
tsx
const [source, setSource] = useState('Hello')
const [text, copy, { copied }] = useClipboard({ source })
setSource('World')
copy() // copies 'World'Options
| Option | Type | Default | Description |
|---|---|---|---|
source | string | — | Default content to copy when copy() is called without arguments |
read | boolean | false | Enable reading clipboard content on copy/cut events |
copiedDuring | number | 1500 | Milliseconds before copied resets to false |
legacy | boolean | false | Fallback to document.execCommand if Clipboard API unavailable |
Return Values
text— current clipboard content (plain string state; updated bycopyand, whenread: true, bycopy/cutevents onwindow).copy(text?)— copy text to the clipboard; accepts a string or a promise producing one, and can be called without arguments to copy thesourceoption.controls.copied—trueafter a successful copy, auto-resets tofalseaftercopiedDuringmilliseconds.controls.isSupported— whether clipboard is supported (native Clipboard API orlegacy: truefallback).controls.copyPending—truewhile acopycall is in flight.
The controls object ({ copied, isSupported, copyPending }) keeps a stable identity while its members are unchanged.
Legacy Mode
Set legacy: true to keep the ability to copy if Clipboard API is not available. It will handle copy with execCommand as fallback.
tsx
const [, copy, { isSupported }] = useClipboard({ legacy: true })Type Declarations
ts
export interface UseClipboardOptions<Source> {
read?: boolean;
source?: Source;
copiedDuring?: number;
legacy?: boolean;
navigator?: Navigator;
}
export type UseClipboardReturn<Optional> = readonly [
text: string,
copy: Optional extends true ? (text?: ClipboardValue) => Promise<void> : (text: ClipboardValue) => Promise<void>,
controls: {
copied: boolean;
isSupported: boolean;
copyPending: boolean;
}
]
type ClipboardValue = string | (() => Promise<string | undefined>)
export function useClipboard(options?: UseClipboardOptions<undefined>): UseClipboardReturn<false>
export function useClipboard(options: UseClipboardOptions<string>): UseClipboardReturn<true>