Back to library
⚛️Reacttypescriptbeginner

useCopyToClipboard Hook

React hook for copying text to clipboard

hooksclipboardutilities

Code

1import { useState } from 'react';
2
3function useCopyToClipboard() {
4  const [copiedText, setCopiedText] = useState<string | null>(null);
5
6  const copy = async (text: string) => {
7    if (!navigator?.clipboard) {
8      console.warn('Clipboard not supported');
9      return false;
10    }
11
12    try {
13      await navigator.clipboard.writeText(text);
14      setCopiedText(text);
15      return true;
16    } catch (error) {
17      console.warn('Copy failed', error);
18      setCopiedText(null);
19      return false;
20    }
21  };
22
23  return { copiedText, copy };
24}
25
26// Usage example
27function CopyButton({ text }: { text: string }) {
28  const { copiedText, copy } = useCopyToClipboard();
29
30  return (
31    <button onClick={() => copy(text)}>
32      {copiedText === text ? 'Copied!' : 'Copy'}
33    </button>
34  );
35}

Quick Tips

  • Click the "Copy" button to copy the code to your clipboard
  • This code is production-ready and can be used in your projects
  • Check out related snippets below for more examples

Build Your Own Snippet Library

Organize your team's code snippets with Snippetly. Share knowledge and boost productivity across your organization.