44 type ReactNode ,
55 type SyntheticEvent ,
66 useCallback ,
7- useEffect ,
87 useId ,
98 useRef ,
109 useState ,
@@ -83,15 +82,13 @@ export function Autocomplete<TOption>({
8382 "data-testid" : testId ,
8483} : AutocompleteProps < TOption > ) {
8584 const inlineInputRef = useRef < HTMLInputElement > ( null ) ;
86- const highlightedValueRef = useRef < string | null > ( null ) ;
8785 const [ managedOpen , setManagedOpen ] = useState ( false ) ;
8886 const [ managedInputValue , setManagedInputValue ] = useState ( "" ) ;
8987 const [ highlightedValue , setHighlightedValue ] = useState < string | null > ( null ) ;
9088 const generatedListboxId = useId ( ) ;
9189 const listboxId = `${ generatedListboxId } -listbox` ;
9290
9391 const updateHighlightedValue = useCallback ( ( newValue : string | null ) => {
94- highlightedValueRef . current = newValue ;
9592 setHighlightedValue ( newValue ) ;
9693 } , [ ] ) ;
9794 const isOpen = controlledOpen ?? managedOpen ;
@@ -166,20 +163,13 @@ export function Autocomplete<TOption>({
166163 [ handleOpenChange , onEscapeKeyDown ] ,
167164 ) ;
168165
169- useEffect ( ( ) => {
170- if (
171- highlightedValue !== null &&
172- ! options . some ( ( option ) => getOptionValue ( option ) === highlightedValue )
173- ) {
174- updateHighlightedValue ( null ) ;
175- }
176- } , [ highlightedValue , options , getOptionValue , updateHighlightedValue ] ) ;
177-
178166 const displayValue = value ? getOptionLabel ( value ) : "" ;
179167 const showClearButton = clearable && value && ! disabled ;
180168 const highlightedIndex = options . findIndex (
181169 ( option ) => getOptionValue ( option ) === highlightedValue ,
182170 ) ;
171+ const effectiveHighlightedValue =
172+ highlightedIndex >= 0 ? highlightedValue : null ;
183173 const activeDescendant =
184174 highlightedIndex >= 0
185175 ? `${ listboxId } -option-${ highlightedIndex } `
@@ -202,7 +192,7 @@ export function Autocomplete<TOption>({
202192 }
203193
204194 const currentIndex = options . findIndex (
205- ( option ) => getOptionValue ( option ) === highlightedValueRef . current ,
195+ ( option ) => getOptionValue ( option ) === highlightedValue ,
206196 ) ;
207197 const nextIndex =
208198 e . key === "ArrowDown"
@@ -226,7 +216,7 @@ export function Autocomplete<TOption>({
226216 }
227217
228218 const highlightedOption = options . find (
229- ( option ) => getOptionValue ( option ) === highlightedValueRef . current ,
219+ ( option ) => getOptionValue ( option ) === highlightedValue ,
230220 ) ;
231221 if ( highlightedOption ) {
232222 handleSelect ( highlightedOption ) ;
@@ -332,7 +322,7 @@ export function Autocomplete<TOption>({
332322 >
333323 < Command
334324 shouldFilter = { false }
335- value = { highlightedValue ?? "" }
325+ value = { effectiveHighlightedValue ?? "" }
336326 onValueChange = { ( newValue ) => {
337327 if ( newValue ) {
338328 updateHighlightedValue ( newValue ) ;
0 commit comments