diff --git a/.changeset/olive-glasses-listen.md b/.changeset/olive-glasses-listen.md new file mode 100644 index 00000000000..5ae87f99651 --- /dev/null +++ b/.changeset/olive-glasses-listen.md @@ -0,0 +1,5 @@ +--- +"@primer/react": patch +--- + +Improve initial `useCombobox` initialization process to avoid race conditions diff --git a/src/drafts/hooks/useCombobox.ts b/src/drafts/hooks/useCombobox.ts index bc7ae732348..c821f069cf5 100644 --- a/src/drafts/hooks/useCombobox.ts +++ b/src/drafts/hooks/useCombobox.ts @@ -97,7 +97,6 @@ export const useCombobox = ({ if (!list.getAttribute('role')) list.setAttribute('role', 'listbox') const cb = new Combobox(input, list, {tabInsertsSuggestions, defaultFirstOption}) - if (isOpenRef.current) cb.start() // By using state instead of a ref here, we trigger the toggleKeyboardEventHandling // effect. Otherwise we'd have to depend on isOpen in this effect to start the instance @@ -116,7 +115,9 @@ export const useCombobox = ({ useEffect( function toggleKeyboardEventHandling() { const wasOpen = isOpenRef.current - isOpenRef.current = isOpen + + // It cannot be open if the instance hasn't yet been initialized + isOpenRef.current = isOpen && comboboxInstance !== null if (isOpen === wasOpen || !comboboxInstance) return