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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Storing a timeout id in a ref survives re-renders without triggering them, unlike state.
- 2Always clear pending timers on unmount so callbacks never fire on a gone component.
- 3Async browser APIs like the clipboard can reject, so wrap them in try/catch.
Related explainers
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
typescript
import { useEffect, useState } from "react"; interface Section { id: string;
Building a scroll-spy hook in React
custom-hooks
intersectionobserver
dom-observation
Intermediate
8 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
javascript
const { pool } = require('./db'); function withTransaction() { return async (req, res, next) => {
A per-request transaction middleware in Express
middleware
database-transactions
connection-pooling
Advanced
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-copy-to-clipboard-button-in-react-explained-javascript-0668/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.