Provides clipboard helpers and tracks whether the last copy action succeeded. The copied flag automatically resets after a configurable timeout.
Usage
import { useClipboard } from '@kuzenbo/hooks';
function Demo() {
const clipboard = useClipboard({ timeout: 2000 });
return (
<div>
<button onClick={() => clipboard.copy('https://kuzenbo.ai')}>
{clipboard.copied ? 'Copied!' : 'Copy URL'}
</button>
{clipboard.error && <p>Failed to copy: {clipboard.error.message}</p>}
</div>
);
}
Function Signature
function useClipboard(
options?: UseClipboardInput
): UseClipboardReturnValue
Parameters
Optional clipboard behavior configuration.Time in milliseconds after which the copied state will reset. Defaults to 2000.
Return Value
Returns an object with the following properties:
copy
(value: string) => Promise<void>
Function to copy value to clipboard. Uses the Clipboard API internally.
Function to reset copied state and clear any error.
Error object if copying failed, otherwise null.
Boolean indicating if the value was copied successfully. Automatically resets to false after the configured timeout.
Examples
Basic Clipboard Copy
import { useClipboard } from '@kuzenbo/hooks';
function CopyButton() {
const clipboard = useClipboard();
return (
<button onClick={() => clipboard.copy('Hello, world!')}>
{clipboard.copied ? 'Copied' : 'Copy'}
</button>
);
}
Custom Timeout
import { useClipboard } from '@kuzenbo/hooks';
function CustomTimeoutExample() {
const clipboard = useClipboard({ timeout: 5000 });
return (
<button onClick={() => clipboard.copy('Custom timeout text')}>
{clipboard.copied ? 'Copied!' : 'Copy'}
</button>
);
}
With Error Handling
import { useClipboard } from '@kuzenbo/hooks';
function ErrorHandlingExample() {
const clipboard = useClipboard();
return (
<div>
<button onClick={() => clipboard.copy('Text to copy')}>
{clipboard.copied ? 'Copied!' : 'Copy'}
</button>
{clipboard.error && (
<div>
<p>Error: {clipboard.error.message}</p>
<button onClick={clipboard.reset}>Reset</button>
</div>
)}
</div>
);
}