Skip to content

Commit 230c1c6

Browse files
MelvinBotmkhutornyi
andcommitted
Fix: avoid duplicate sort in initiallyFocusedKey computation
Replace the full array sort in the useState initializer with a linear scan that finds the minimum selected item using the comparator directly. This eliminates the duplicate sort while keeping initiallyFocusedKey stable across re-renders (no search-clear scroll bug). Co-authored-by: mkhutornyi <mkhutornyi@users.noreply.github.com>
1 parent b797082 commit 230c1c6

1 file changed

Lines changed: 9 additions & 2 deletions

File tree

src/components/Search/SearchMultipleSelectionPicker.tsx

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,15 @@ function SearchMultipleSelectionPicker<T extends string | string[]>({
3636
const [initialSelectedIDs] = useState(() => new Set((initiallySelectedItems ?? []).map((item) => item.value.toString())));
3737
const [selectedItemIDs, setSelectedItemIDs] = useState(() => initialSelectedIDs);
3838
const [initiallyFocusedKey] = useState(() => {
39-
const sorted = [...items].sort((a, b) => sortOptionsWithEmptyValue(a.value.toString(), b.value.toString(), localeCompare));
40-
return sorted.find((item) => initialSelectedIDs.has(item.value.toString()))?.name;
39+
let minItem: SearchMultipleSelectionPickerItem<T> | undefined;
40+
for (const item of items) {
41+
if (initialSelectedIDs.has(item.value.toString())) {
42+
if (!minItem || sortOptionsWithEmptyValue(item.value.toString(), minItem.value.toString(), localeCompare) < 0) {
43+
minItem = item;
44+
}
45+
}
46+
}
47+
return minItem?.name;
4148
});
4249

4350
const searchLower = debouncedSearchTerm.toLowerCase();

0 commit comments

Comments
 (0)