javascript 32 lines · 7 steps

A copy-to-clipboard button in React

A React component that copies text, flashes a confirmation, and cleans up its timer safely.

Explained by highlit
1import { useState, useRef, useEffect, useCallback } from 'react';
2 
3export function CopyButton({ text, label = 'Copy' }) {
4 const [copied, setCopied] = useState(false);
5 const timeoutRef = useRef(null);
6 
7 useEffect(() => {
8 return () => clearTimeout(timeoutRef.current);
9 }, []);
10 
11 const handleCopy = useCallback(async () => {
12 try {
13 await navigator.clipboard.writeText(text);
14 setCopied(true);
15 clearTimeout(timeoutRef.current);
16 timeoutRef.current = setTimeout(() => setCopied(false), 2000);
17 } catch (err) {
18 console.error('Failed to copy to clipboard', err);
19 }
20 }, [text]);
21 
22 return (
23 <button
24 type="button"
25 onClick={handleCopy}
26 className={`copy-button${copied ? ' copy-button--copied' : ''}`}
27 aria-live="polite"
28 >
29 {copied ? 'Copied!' : label}
30 </button>
31 );
32}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Storing a timeout id in a ref survives re-renders without triggering them, unlike state.
  2. 2Always clear pending timers on unmount so callbacks never fire on a gone component.
  3. 3Async browser APIs like the clipboard can reject, so wrap them in try/catch.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A copy-to-clipboard button in React — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code