Back to all snippets
Library/React/useCopyToClipboard Hook
typescriptbeginnerhooksutilitiesclipboard

How to implement useCopyToClipboard Hook in Typescript

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.

Code Snippet

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}

What is useCopyToClipboard Hook?

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.

How It Works

  1. 1navigator.clipboard.writeText(text) is called asynchronously.
  2. 2On success, copiedText state is updated with the copied string.
  3. 3On failure, copiedText is reset to null and a warning is logged.
  4. 4The component can read copiedText to show a confirmation badge or icon.

Common Use Cases

  • Code blocks - Add a Copy button to syntax-highlighted code
  • Referral links - One-click copy of share URLs
  • API keys - Copy credentials without selecting text manually
  • Color pickers - Copy hex values to clipboard

Key Benefits

  • Uses the modern async Clipboard API
  • Tracks copied text for confirmation UI feedback
  • Falls back gracefully if clipboard is unavailable
  • Tiny hook with no dependencies

Common Mistakes to Avoid

  • Not resetting copiedText after a timeout — users expect the 'Copied!' state to clear after 2–3 seconds.
  • Calling copy in a non-secure context (HTTP) — navigator.clipboard requires HTTPS.
  • Not handling the Promise rejection — always add a catch or the failure is silent.

Quick Tips

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

Frequently Asked Questions

Does the Clipboard API work in all browsers?

The async Clipboard API works in all modern browsers over HTTPS. It requires a user gesture (click) to work.

How do I reset the 'Copied' state after a few seconds?

Use a useEffect that watches copiedText and calls setTimeout to reset it to null after 2000 ms.

What is the fallback for HTTP or older browsers?

Use document.execCommand('copy') with a temporary textarea as a fallback for non-HTTPS contexts.

About This Typescript Code Snippet

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.

Tags: hooks, utilities, clipboard  | Language: typescript  | Difficulty: beginner  | Category: React

Build Your Own Snippet Library

Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.