Skip to content

useClipboard

Saurav-TB-Pandey edited this page Aug 8, 2026 · 2 revisions

useClipboard

Reads and writes text to the user's clipboard, managing a temporary "copied" state. Great for "Copy to Clipboard" buttons.

Usage Examples

Basic (Minimum Parameters)

The simplest possible implementation, using the default 2-second reset timeout.

import { useClipboard } from 'react-hook-lab';

function BasicCopy() {
  const { copy, copied } = useClipboard();

  return (
    <button onClick={() => copy("Hello World!")}>
      {copied ? "Copied!" : "Copy Text"}
    </button>
  );
}

Common (Standard Usage)

Handling potential clipboard errors (e.g. when the page is not served over HTTPS or lacks focus).

import { useClipboard } from 'react-hook-lab';

function ErrorHandlingCopy({ textToCopy }) {
  const { copy, copied, error } = useClipboard(1500); // Reset state after 1.5 seconds

  const handleCopy = async () => {
    const success = await copy(textToCopy);
    if (!success) {
      console.warn("Fallback required for copying");
    }
  };

  return (
    <div>
      <button onClick={handleCopy}>
        {copied ? "✅ Copied!" : "📋 Copy Code"}
      </button>
      {error && <span style={{color: 'red'}}> {error.message}</span>}
    </div>
  );
}

Advanced (All Parameters)

An exhaustive example utilizing all properties, including dynamic timeouts based on state.

import { useClipboard } from 'react-hook-lab';
import { useState } from 'react';

function AdvancedCopy() {
  const [timeout, setTimeoutVal] = useState(3000);
  const { copy, copied, error } = useClipboard(timeout);

  return (
    <div>
      <input 
        type="number" 
        value={timeout} 
        onChange={e => setTimeoutVal(Number(e.target.value))} 
        step={100}
      />
      <label> Reset Timeout (ms)</label>
      <br/><br/>
      <button onClick={() => copy(`Copied with a ${timeout}ms reset!`)} disabled={copied}>
        {copied ? `Waiting ${timeout}ms...` : "Copy dynamic text"}
      </button>
      {error && <p>Failed: {error.message}</p>}
    </div>
  );
}

API Reference

Parameters

  • timeout
    • Type: number
    • Default: 2000
    • Description: The duration in milliseconds before the copied state automatically resets to false after a successful copy operation.

Return Object

Returns an object containing:

  • copied (boolean): true if the text was successfully copied and the timeout hasn't elapsed. false otherwise.
  • error (Error | null): The caught Error if the clipboard operation fails (e.g., Clipboard API not supported or permission denied).
  • copy ((text: string) => Promise<boolean>): The asynchronous function to execute the copy operation. Returns a promise resolving to true on success, or false on failure.

Clone this wiki locally