HooksuseClipboard

useClipboard()

The useClipboard() hook provides a simple interface for interacting with the Clipboard API, handling copy/paste operations, and managing UI feedback states.

Import

typescript
import { useClipboard } from 'the-react-hooks';

Usage

Click "Paste Text" to see clipboard content...
Component.tsx
import { useClipboard } from 'the-react-hooks';

export const Component = () => {
  const { copy, paste, hasCopied, clipboardValue } = useClipboard({ timeout: 2000 });

  return (
    <div>
      <button onClick={() => copy('Hello World')}>
        {hasCopied ? 'Copied!' : 'Copy "Hello World"'}
      </button>

      <button onClick={paste}>Paste from Clipboard</button>
      <p>Clipboard content: {clipboardValue}</p>
    </div>
  );
}

API

Arguments

Accepts an optional options object:
  • timeout – number (Optional) Duration in milliseconds for the hasCopied state to remain true. Defaults to 2000.

Returns

Returns an object with the following properties:
  • copy – (text: string) => Promise<boolean> Function to copy text to the clipboard. Returns true if successful.
  • paste – () => Promise<string | null> Function to read text from the clipboard. Returns the text or null if failed.
  • hasCopied – boolean True if text was recently copied. Resets automatically after the timeout.
  • clipboardValue – string | null The last value read from the clipboard using the paste function.
  • error – Error | null Error object if the copy or paste operation fails (e.g., permission denied).
  • reset – () => void Function to manually reset the hasCopied state and errors.