# useCopyToClipboard

> Copy text to clipboard with a temporary "copied" state.

Canonical URL: https://taut-ui.com/docs/hooks/use-copy-to-clipboard

A React hook that wraps the Clipboard API with a built-in timeout to reset the copied state. Useful for copy buttons that show brief confirmation feedback.

## Installation [#installation]

**CLI**

```bash
npx shadcn@latest add https://taut-ui.com/r/use-copy-to-clipboard.json
```

**Manual**

- Copy and paste the following code into your project.

```tsx title="hooks/use-copy-to-clipboard.ts"
"use client";

import * as React from "react";

export function useCopyToClipboard({
  timeout = 2000,
  onCopy,
}: {
  timeout?: number;
  onCopy?: () => void;
} = {}): { copyToClipboard: (value: string) => void; isCopied: boolean } {
  const [isCopied, setIsCopied] = React.useState(false);
  const timeoutIdRef = React.useRef<NodeJS.Timeout | null>(null);

  const copyToClipboard = (value: string): void => {
    if (typeof window === "undefined" || !navigator.clipboard.writeText) {
      return;
    }

    if (!value) return;

    navigator.clipboard.writeText(value).then(() => {
      if (timeoutIdRef.current) {
        clearTimeout(timeoutIdRef.current);
      }
      setIsCopied(true);

      if (onCopy) {
        onCopy();
      }

      if (timeout !== 0) {
        timeoutIdRef.current = setTimeout(() => {
          setIsCopied(false);
          timeoutIdRef.current = null;
        }, timeout);
      }
    }, console.error);
  };

  React.useEffect(() => {
    return (): void => {
      if (timeoutIdRef.current) {
        clearTimeout(timeoutIdRef.current);
      }
    };
  }, []);

  return { copyToClipboard, isCopied };
}
```

- Update the import paths to match your project setup.

## Usage [#usage]

### Basic [#basic]

```tsx
import { useCopyToClipboard } from "@/hooks/use-copy-to-clipboard";

function CopyButton({ text }: { text: string }) {
  const { copyToClipboard, isCopied } = useCopyToClipboard();

  return (
    <button onClick={() => copyToClipboard(text)}>
      {isCopied ? "Copied!" : "Copy"}
    </button>
  );
}
```

### Custom timeout [#custom-timeout]

The `isCopied` state resets after 2 seconds by default. You can change this:

```tsx
const { copyToClipboard, isCopied } = useCopyToClipboard({ timeout: 3000 });
```

Set `timeout` to `0` to keep `isCopied` as `true` indefinitely (until the component unmounts).

### Callback on copy [#callback-on-copy]

Run a side effect when a copy succeeds:

```tsx
const { copyToClipboard, isCopied } = useCopyToClipboard({
  onCopy: () => console.log("Copied to clipboard"),
});
```

### With icon swap [#with-icon-swap]

A common pattern — swap the icon briefly to confirm the copy:

```tsx
import { CheckIcon, CopyIcon } from "lucide-react";
import { useCopyToClipboard } from "@/hooks/use-copy-to-clipboard";
import { Button } from "@/components/ui/button";

function CopyButton({ value }: { value: string }) {
  const { copyToClipboard, isCopied } = useCopyToClipboard();

  return (
    <Button
      aria-label="Copy to clipboard"
      onClick={() => copyToClipboard(value)}
      size="icon"
      variant="outline"
    >
      {isCopied ? (
        <CheckIcon aria-hidden="true" />
      ) : (
        <CopyIcon aria-hidden="true" />
      )}
    </Button>
  );
}
```

## API [#api]

```tsx
function useCopyToClipboard(options?: {
  timeout?: number;
  onCopy?: () => void;
}): {
  copyToClipboard: (value: string) => void;
  isCopied: boolean;
};
```

### Options [#options]

| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `timeout` | `number` | `2000` | Milliseconds before `isCopied` resets to `false`. Set to `0` to keep it `true`. |
| `onCopy` | `() => void` | — | Callback fired after a successful copy. |

### Return value [#return-value]

| Property | Type | Description |
|----------|------|-------------|
| `copyToClipboard` | `(value: string) => void` | Call with the text to copy. No-op if `value` is empty or clipboard API is unavailable. |
| `isCopied` | `boolean` | `true` for `timeout` ms after a successful copy, then resets. |
