useHooks.iov4.1.2
DocsBlogGitHub
Hooks
No hooks found in any category.

useClipboard

browser

Installation

npx usehooks-cli@latest add use-clipboard

Description

A React hook for interacting with the clipboard API to copy text content with state management, error handling, and automatic feedback.

Return Type

UseClipboardReturn
PropertyTypeDescription
valuestring | nullThe last successfully copied text value
copy(text: string) => Promise<boolean>Copy text to clipboard, returns true if successful
copiedbooleanTrue if text was recently copied (resets after 2 seconds)
errorstring | nullError message if copy operation failed

Examples

Copy Button with Feedback

Basic copy functionality with visual feedback

1const { copy, copied, error } = useClipboard(); 2const [text] = useState('Hello, World!'); 3 4const handleCopy = async () => { 5 await copy(text); 6}; 7 8return ( 9 <div> 10 <p>{text}</p> 11 <button onClick={handleCopy} disabled={copied}> 12 {copied ? 'Copied!' : 'Copy'} 13 </button> 14 {error && <p style={{ color: 'red' }}>Error: {error}</p>} 15 </div> 16);

Copy Code Snippet

Copying code with syntax highlighting and feedback

1const { copy, copied, error } = useClipboard(); 2 3const CodeBlock = ({ code, language }) => { 4 const handleCopyCode = async () => { 5 const success = await copy(code); 6 if (success) { 7 // Optional: Show toast notification 8 showToast('Code copied to clipboard!'); 9 } 10 }; 11 12 return ( 13 <div className="code-block"> 14 <div className="code-header"> 15 <span>{language}</span> 16 <button 17 onClick={handleCopyCode} 18 className={copied ? 'copied' : ''} 19 > 20 {copied ? '✓ Copied' : '📋 Copy'} 21 </button> 22 </div> 23 <pre><code>{code}</code></pre> 24 {error && <div className="error">{error}</div>} 25 </div> 26 ); 27};

Share URL Functionality

Copying current page URL with user feedback

1const { copy, copied, value, error } = useClipboard(); 2 3const ShareButton = () => { 4 const handleShareUrl = async () => { 5 const currentUrl = window.location.href; 6 const success = await copy(currentUrl); 7 8 if (success) { 9 // Optional: Analytics tracking 10 trackEvent('url_shared', { url: currentUrl }); 11 } 12 }; 13 14 return ( 15 <div className="share-section"> 16 <button onClick={handleShareUrl} className="share-btn"> 17 {copied ? '🎉 Link Copied!' : '🔗 Share This Page'} 18 </button> 19 20 {copied && value && ( 21 <div className="copied-url"> 22 <small>Copied: {value}</small> 23 </div> 24 )} 25 26 {error && ( 27 <div className="error-message"> 28 Failed to copy: {error} 29 </div> 30 )} 31 </div> 32 ); 33};

Dependencies

react

Notes

  • Requires a secure context (HTTPS) for the Clipboard API to work
  • Automatically resets the 'copied' state after 2 seconds
  • Gracefully handles browsers that don't support the Clipboard API
  • Returns boolean from copy function to indicate success/failure
  • Stores the last successfully copied value for reference
  • Provides detailed error messages for debugging

Implementation

1"use client"; 2 3import { useState, useCallback } from "react"; 4 5interface UseClipboardReturn { 6 value: string | null; 7 copy: (text: string) => Promise<boolean>; 8 copied: boolean; 9 error: string | null; 10} 11 12export function useClipboard(): UseClipboardReturn { 13 const [value, setValue] = useState<string | null>(null); 14 const [copied, setCopied] = useState(false); 15 const [error, setError] = useState<string | null>(null); 16 17 const copy = useCallback(async (text: string): Promise<boolean> => { 18 if (!navigator?.clipboard) { 19 setError("Clipboard not supported"); 20 return false; 21 } 22 23 try { 24 await navigator.clipboard.writeText(text); 25 setValue(text); 26 setCopied(true); 27 setError(null); 28 29 // Reset copied state after 2 seconds 30 setTimeout(() => setCopied(false), 2000); 31 32 return true; 33 } catch (err) { 34 setError(err instanceof Error ? err.message : "Failed to copy"); 35 setCopied(false); 36 return false; 37 } 38 }, []); 39 40 return { 41 value, 42 copy, 43 copied, 44 error, 45 }; 46} 47