@@ -19,17 +19,17 @@ export default function useDelayState<T>(
1919 defaultValue : T | ( ( ) => T ) ,
2020) : [ T , SetDelayState < T > ] {
2121 const [ value , setValue ] = React . useState ( defaultValue ) ;
22- const rafRef = React . useRef < number | null > ( null ) ;
23- const timeoutRef = React . useRef < ReturnType < typeof setTimeout > | null > ( null ) ;
22+ const delayRef = React . useRef < [ isRaf : boolean , delay : number ] | null > ( null ) ;
2423
2524 const cancelPending = useEvent ( ( ) => {
26- if ( rafRef . current !== null ) {
27- raf . cancel ( rafRef . current ) ;
28- rafRef . current = null ;
29- }
30- if ( timeoutRef . current !== null ) {
31- clearTimeout ( timeoutRef . current ) ;
32- timeoutRef . current = null ;
25+ if ( delayRef . current ) {
26+ const [ isRaf , delay ] = delayRef . current ;
27+ if ( isRaf ) {
28+ raf . cancel ( delay ) ;
29+ } else {
30+ clearTimeout ( delay ) ;
31+ }
32+ delayRef . current = null ;
3333 }
3434 } ) ;
3535
@@ -43,21 +43,19 @@ export default function useDelayState<T>(
4343 typeof immediatelyOrDelay === 'object' &&
4444 'ms' in immediatelyOrDelay
4545 ) {
46- timeoutRef . current = setTimeout (
47- ( ) => setValue ( nextValue ) ,
48- immediatelyOrDelay . ms ,
49- ) ;
46+ delayRef . current = [
47+ false ,
48+ window . setTimeout ( ( ) => setValue ( nextValue ) , immediatelyOrDelay . ms ) ,
49+ ] ;
5050 } else {
5151 const frame =
5252 typeof immediatelyOrDelay === 'object'
5353 ? immediatelyOrDelay . frame
5454 : undefined ;
55- rafRef . current = raf ( ( ) => setValue ( nextValue ) , frame ) ;
55+ delayRef . current = [ true , raf ( ( ) => setValue ( nextValue ) , frame ) ] ;
5656 }
5757 } ,
5858 ) ;
5959
60- React . useEffect ( ( ) => cancelPending , [ cancelPending ] ) ;
61-
6260 return [ value , setDelayValue ] ;
6361}
0 commit comments