Skip to main content

Function: useClipboard()

@arolariu/components


@arolariu/components / useClipboard

Function: useClipboard()

useClipboard(options?): UseClipboardReturn

Defined in: hooks/useClipboard.tsx:84

Copies text to the clipboard with success/error state management.

Parameters

options?

UseClipboardOptions = {}

Configuration options for the hook.

Returns

UseClipboardReturn

An object containing the copied state, copy function, and any error.

Remarks

This hook provides a simple interface for copying text to the clipboard using the Clipboard API. It manages the copied state that automatically resets after a configurable timeout, and handles errors gracefully when the Clipboard API is unavailable or the operation fails.

The hook is SSR-safe and will handle the case where navigator.clipboard is not available (e.g., in non-secure contexts or older browsers).

Examples

function CopyButton({textToCopy}: {textToCopy: string}) {
const {copied, copy, error} = useClipboard({timeout: 3000});

return (
<div>
<button onClick={() => copy(textToCopy)}>
{copied ? "Copied!" : "Copy to clipboard"}
</button>
{error && <span>Failed to copy: {error.message}</span>}
</div>
);
}
function ShareLink({url}: {url: string}) {
const {copied, copy} = useClipboard();

return (
<button onClick={() => copy(url)} disabled={copied}>
{copied ? "✓ Copied" : "Share link"}
</button>
);
}
// was this page useful?