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
const express = require('express'); const router = express.Router(); const { pool } = require('../db'); const redis = require('../redis');
Building a health check endpoint in Express
health-check
timeouts
promise-race
Intermediate
9 steps
javascript
'use client'; import { useEffect } from 'react'; import * as Sentry from '@sentry/nextjs';
How a Next.js error boundary recovers
error-boundary
error-handling
observability
Intermediate
8 steps
typescript
type ResizeCallback = (size: { width: number; height: number }) => void; export function observeResize(callback: ResizeCallback, delay = 150) { let timeoutId: ReturnType<typeof setTimeout> | undefined;
Debouncing window resize in TypeScript
debounce
closures
event-listeners
Intermediate
6 steps
javascript
const MAX_BATCH_SIZE = 20; const FLUSH_INTERVAL = 5000; const ENDPOINT = '/api/analytics';
Batching analytics events in the browser
batching
buffering
sendbeacon
Intermediate
10 steps
javascript
export function diffIds(current, desired) { const currentSet = new Set(current); const desiredSet = new Set(desired);
Diffing sets to sync group membership
set-operations
diffing
transactions
Intermediate
8 steps
javascript
class HistoryStack { constructor(initial = '', limit = 100) { this.past = []; this.present = initial;
Building an undo/redo history stack
undo-redo
state-management
debouncing
Intermediate
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.