Copy text to clipboard with React hook
Quick Answer
useCopyToClipboard returns a copy function that writes text to the system clipboard using the async Clipboard API. It also tracks what was last copied so you can show a visual confirmation.
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] as const;
24}useCopyToClipboard uses the modern navigator.clipboard API to write text to the system clipboard asynchronously. It tracks what was last copied so you can show a confirmation state (e.g. changing a Copy button to Copied!) for a better user experience.
The async Clipboard API works in all modern browsers over HTTPS. It requires a user gesture (click) to work.
Use a useEffect that watches copiedText and calls setTimeout to reset it to null after 2000 ms.
Use document.execCommand('copy') with a temporary textarea as a fallback for non-HTTPS contexts.
This free typescript code snippet for usecopytoclipboard hook is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this beginner-level example will help you implement usecopytoclipboard hook quickly and correctly.
All snippets in the Snippetly library follow typescript best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses typescript.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.