h3/use's logo

h3/use

Command Palette

Search for a command to run...

useCopyToClipboard

Copies text to the clipboard.

useCopyToClipboard
This component uses the useCopyToClipboard hook to copy text to the clipboard.

Installation

Props

PropTypeDefaultDescription
durationnumber1500The duration of the copied state

Data

PropTypeDescription
copiedbooleanWhether the text has been copied
copyfunctionThe function to copy the text to the clipboard

Key Features & Details

Browser Support & Fallback

  • Uses the modern navigator.clipboard.writeText API if available.
  • Falls back to a legacy method using a hidden textarea and document.execCommand('copy') for older browsers.

Error Handling

  • If copying fails, the hook logs an error and returns false from the copy function.

Copied State & Duration

  • The copied state is set to true when copying succeeds, and automatically resets to false after the specified duration (in ms).

Cleanup

  • Any pending timeout is cleared when the component unmounts, preventing memory leaks or unexpected state changes.

Best Practices & Caveats

  • The hook is client-side only; on the server, it does not interact with the clipboard.
  • Some browsers may block clipboard access unless triggered by a user gesture (e.g., a button click).
  • The fallback method may not work in all environments (e.g., some mobile browsers).
  • For best performance, avoid creating new copy functions on every render.

Examples

Basic Usage

const { copied, copy } = useCopyToClipboard();
<button onClick={() => copy('Hello!')}>{copied ? 'Copied!' : 'Copy'}</button>;

Custom Duration

const { copied, copy } = useCopyToClipboard(3000);

Handling Copy Result

const { copy } = useCopyToClipboard();
const handleCopy = async () => {
  const success = await copy('Some text');
  if (success) alert('Copied!');
};