File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -131,13 +131,21 @@ export function useTimedState<T>(
131131 shouldExpire ?: ( value : T ) => boolean
132132) : [ T | null , Dispatch < SetStateAction < T | null > > ] {
133133 const [ value , setValue ] = useState < T | null > ( null )
134+ const shouldExpireRef = useRef < typeof shouldExpire > ( )
135+
136+ // Keep the ref updated with the latest predicate without tying the timer effect
137+ // to the predicate's identity (which may change across renders).
138+ useEffect ( ( ) => {
139+ shouldExpireRef . current = shouldExpire
140+ } , [ shouldExpire ] )
134141
135142 useEffect ( ( ) => {
136143 if ( value === null ) return
137- if ( shouldExpire && ! shouldExpire ( value ) ) return
144+ const predicate = shouldExpireRef . current
145+ if ( predicate && ! predicate ( value ) ) return
138146 const timer = setTimeout ( ( ) => setValue ( null ) , duration )
139147 return ( ) => clearTimeout ( timer )
140- } , [ value , duration , shouldExpire ] )
148+ } , [ value , duration ] )
141149
142150 return [ value , setValue ]
143151}
You can’t perform that action at this time.
0 commit comments