1- import { useState , useCallback } from "react"
1+ import { useState , useCallback , useEffect , useRef } from "react"
22
33/**
44 * Options for copying text to clipboard
@@ -33,15 +33,24 @@ export const copyToClipboard = async (text: string, options?: CopyOptions): Prom
3333 */
3434export const useCopyToClipboard = ( feedbackDuration = 2000 ) => {
3535 const [ showCopyFeedback , setShowCopyFeedback ] = useState ( false )
36+ const timeoutRef = useRef < NodeJS . Timeout | null > ( null )
3637
3738 const copyWithFeedback = useCallback (
3839 async ( text : string , e ?: React . MouseEvent ) => {
3940 e ?. stopPropagation ( )
4041
42+ // Clear any existing timeout
43+ if ( timeoutRef . current ) {
44+ clearTimeout ( timeoutRef . current )
45+ }
46+
4147 const success = await copyToClipboard ( text , {
4248 onSuccess : ( ) => {
4349 setShowCopyFeedback ( true )
44- setTimeout ( ( ) => setShowCopyFeedback ( false ) , feedbackDuration )
50+ timeoutRef . current = setTimeout ( ( ) => {
51+ setShowCopyFeedback ( false )
52+ timeoutRef . current = null
53+ } , feedbackDuration )
4554 } ,
4655 } )
4756
@@ -50,6 +59,15 @@ export const useCopyToClipboard = (feedbackDuration = 2000) => {
5059 [ feedbackDuration ] ,
5160 )
5261
62+ // Cleanup timeout on unmount
63+ useEffect ( ( ) => {
64+ return ( ) => {
65+ if ( timeoutRef . current ) {
66+ clearTimeout ( timeoutRef . current )
67+ }
68+ }
69+ } , [ ] )
70+
5371 return {
5472 showCopyFeedback,
5573 copyWithFeedback,
0 commit comments