JavaScript Snippet

React useCopyToClipboard Hook

Difficulty: Medium

A copy-to-clipboard button needs to do three things: write to the clipboard, surface success or failure to the UI, and reset the success indicator after a short delay. This snippet covers a status-aware hook with a one-shot success flag, a fallback variant for older browsers, and a copy-with-format helper that writes both plain text and rich HTML. Drop it next to any 'Copy code' button.

Code Snippets
/

React useCopyToClipboard Hook

React useCopyToClipboard Hook

A copy-to-clipboard button needs to do three things: write to the clipboard, surface success or failure to the UI, and reset the success indicator after a short delay. This snippet covers a status-aware hook with a one-shot success flag, a fallback variant for older browsers, and a copy-with-format helper that writes both plain text and rich HTML. Drop it next to any 'Copy code' button.

JavaScript
Medium
3 snippets
react
hooks
code-template
js-web-apis

803 views

21

The hook returns a status string (idle, copied, error) so UI can swap a tooltip or icon without storing a separate boolean. navigator.clipboard.writeText is async and rejects when the document does not have user-activation focus, hence the try/catch. The auto-reset via setTimeout is what turns the button back from a checkmark to the copy icon a moment later. The resolved boolean lets the caller chain side effects without subscribing to the status.