Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
160 changes: 77 additions & 83 deletions src/components/Search/SearchSingleSelectionPicker.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import React, {useCallback, useEffect, useMemo, useState} from 'react';
// eslint-disable-next-line no-restricted-imports
import SelectionList from '@components/SelectionListWithSections';
import SingleSelectListItem from '@components/SelectionListWithSections/SingleSelectListItem';
import React, {useEffect, useState} from 'react';
import SingleSelectListItem from '@components/SelectionList/ListItem/SingleSelectListItem';
import SelectionList from '@components/SelectionList/SelectionListWithSections';
import useDebouncedState from '@hooks/useDebouncedState';
import useLocalize from '@hooks/useLocalize';
import Navigation from '@libs/Navigation/Navigation';
Expand Down Expand Up @@ -44,98 +43,93 @@ function SearchSingleSelectionPicker({
setSelectedItem(initiallySelectedItem);
}, [initiallySelectedItem]);

const {sections, noResultsFound} = useMemo(() => {
const initiallySelectedItemSection = initiallySelectedItem?.name.toLowerCase().includes(debouncedSearchTerm?.toLowerCase())
? [
{
text: initiallySelectedItem.name,
keyForList: initiallySelectedItem.value,
isSelected: selectedItem?.value === initiallySelectedItem.value,
value: initiallySelectedItem.value,
},
]
: [];
const remainingItemsSection = items
.filter((item) => item?.value !== initiallySelectedItem?.value && item?.name?.toLowerCase().includes(debouncedSearchTerm?.toLowerCase()))
.sort((a, b) => sortOptionsWithEmptyValue(a.name.toString(), b.name.toString(), localeCompare))
.map((item) => ({
text: item.name,
keyForList: item.value,
isSelected: selectedItem?.value === item.value,
value: item.value,
}));
const isEmpty = !initiallySelectedItemSection.length && !remainingItemsSection.length;
return {
sections: isEmpty
? []
: [
{
title: undefined,
data: initiallySelectedItemSection,
shouldShow: initiallySelectedItemSection.length > 0,
indexOffset: 0,
},
{
title: pickerTitle,
data: remainingItemsSection,
shouldShow: remainingItemsSection.length > 0,
indexOffset: initiallySelectedItemSection.length,
},
],
noResultsFound: isEmpty,
};
}, [initiallySelectedItem, selectedItem?.value, items, pickerTitle, debouncedSearchTerm, localeCompare]);

const onSelectItem = useCallback(
(item: Partial<OptionData & SearchSingleSelectionPickerItem>) => {
if (!item.text || !item.keyForList || !item.value) {
return;
}
if (shouldAutoSave) {
onSaveSelection(item.isSelected ? '' : item.value);
Navigation.goBack(backToRoute ?? ROUTES.SEARCH_ADVANCED_FILTERS.getRoute());
return;
}
if (!item.isSelected) {
setSelectedItem({name: item.text, value: item.value});
}
},
[shouldAutoSave, backToRoute, onSaveSelection],
);
const initiallySelectedItemSection = initiallySelectedItem?.name.toLowerCase().includes(debouncedSearchTerm?.toLowerCase())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❌ PERF-6 (docs)

The sections computation is expensive (filtering, sorting, mapping on every render) and should be memoized with useMemo. Without memoization, the entire items array is processed on every render, which can cause performance issues with large lists.

Suggested fix:

const {sections, noResultsFound} = useMemo(() => {
    const initiallySelectedItemSection = initiallySelectedItem?.name.toLowerCase().includes(debouncedSearchTerm?.toLowerCase())
        ? [
              {
                  text: initiallySelectedItem.name,
                  keyForList: initiallySelectedItem.value,
                  isSelected: selectedItem?.value === initiallySelectedItem.value,
                  value: initiallySelectedItem.value,
              },
          ]
        : [];

    const remainingItemsSection = items
        .filter((item) => item.value !== initiallySelectedItem?.value && item.name.toLowerCase().includes(debouncedSearchTerm?.toLowerCase()))
        .sort((a, b) => sortOptionsWithEmptyValue(a.name.toString(), b.name.toString(), localeCompare))
        .map((item) => ({
            text: item.name,
            keyForList: item.value,
            isSelected: selectedItem?.value === item.value,
            value: item.value,
        }));

    const noResultsFound = !initiallySelectedItemSection.length && !remainingItemsSection.length;

    const sections = noResultsFound
        ? []
        : [
              {
                  title: undefined,
                  data: initiallySelectedItemSection,
                  sectionIndex: 0,
              },
              {
                  title: pickerTitle,
                  data: remainingItemsSection,
                  sectionIndex: 1,
              },
          ];
    
    return {sections, noResultsFound};
}, [initiallySelectedItem, selectedItem?.value, items, pickerTitle, debouncedSearchTerm, localeCompare]);

Please rate this suggestion with 👍 or 👎 to help us improve! Reactions are used to monitor reviewer efficiency.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AFAIK this component can be compiled by React Compiler so the useMemo is not needed

? [
{
text: initiallySelectedItem.name,
keyForList: initiallySelectedItem.value,
isSelected: selectedItem?.value === initiallySelectedItem.value,
value: initiallySelectedItem.value,
},
]
: [];

const remainingItemsSection = items
.filter((item) => item.value !== initiallySelectedItem?.value && item.name.toLowerCase().includes(debouncedSearchTerm?.toLowerCase()))
.sort((a, b) => sortOptionsWithEmptyValue(a.name.toString(), b.name.toString(), localeCompare))
.map((item) => ({
text: item.name,
keyForList: item.value,
isSelected: selectedItem?.value === item.value,
value: item.value,
}));

const noResultsFound = !initiallySelectedItemSection.length && !remainingItemsSection.length;

const sections = noResultsFound
? []
: [
{
title: undefined,
data: initiallySelectedItemSection,
sectionIndex: 0,
},
{
title: pickerTitle,
data: remainingItemsSection,
sectionIndex: 1,
},
];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❌ PERF-6 (docs)

The onSelectItem function should be wrapped in useCallback to prevent unnecessary re-renders of the SelectionList component. Without memoization, a new function reference is created on every render, causing SelectionList to re-render even when props haven't meaningfully changed.

Suggested fix:

const onSelectItem = useCallback(
    (item: Partial<OptionData & SearchSingleSelectionPickerItem>) => {
        if (\!item.text || \!item.keyForList || \!item.value) {
            return;
        }
        if (shouldAutoSave) {
            onSaveSelection(item.isSelected ? '' : item.value);
            Navigation.goBack(backToRoute ?? ROUTES.SEARCH_ADVANCED_FILTERS.getRoute());
            return;
        }
        if (\!item.isSelected) {
            setSelectedItem({name: item.text, value: item.value});
        }
    },
    [shouldAutoSave, backToRoute, onSaveSelection],
);

Please rate this suggestion with 👍 or 👎 to help us improve! Reactions are used to monitor reviewer efficiency.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AFAIK this component can be compiled by React Compiler so the useMemo is not needed

const resetChanges = useCallback(() => {
const onSelectItem = (item: Partial<OptionData & SearchSingleSelectionPickerItem>) => {
if (!item.text || !item.keyForList || !item.value) {
return;
}
if (shouldAutoSave) {
onSaveSelection(item.isSelected ? '' : item.value);
Navigation.goBack(backToRoute ?? ROUTES.SEARCH_ADVANCED_FILTERS.getRoute());
return;
}
if (!item.isSelected) {
setSelectedItem({name: item.text, value: item.value});
}
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❌ PERF-6 (docs)

The resetChanges function should be wrapped in useCallback to prevent unnecessary re-renders of child components. Without memoization, a new function reference is created on every render, causing the SearchFilterPageFooterButtons component to re-render unnecessarily.

Suggested fix:

const resetChanges = useCallback(() => {
    setSelectedItem(undefined);
}, []);

Please rate this suggestion with 👍 or 👎 to help us improve! Reactions are used to monitor reviewer efficiency.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AFAIK this component can be compiled by React Compiler so the useMemo is not needed

const resetChanges = () => {
setSelectedItem(undefined);
}, []);
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❌ PERF-6 (docs)

The applyChanges function should be wrapped in useCallback to prevent unnecessary re-renders of child components. Without memoization, a new function reference is created on every render, causing the SearchFilterPageFooterButtons component to re-render unnecessarily.

Suggested fix:

const applyChanges = useCallback(() => {
    onSaveSelection(selectedItem?.value);
    Navigation.goBack(backToRoute ?? ROUTES.SEARCH_ADVANCED_FILTERS.getRoute());
}, [onSaveSelection, selectedItem?.value, backToRoute]);

Please rate this suggestion with 👍 or 👎 to help us improve! Reactions are used to monitor reviewer efficiency.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AFAIK this component can be compiled by React Compiler so the useMemo is not needed

const applyChanges = useCallback(() => {
const applyChanges = () => {
onSaveSelection(selectedItem?.value);
Navigation.goBack(backToRoute ?? ROUTES.SEARCH_ADVANCED_FILTERS.getRoute());
}, [onSaveSelection, selectedItem?.value, backToRoute]);

const footerContent = useMemo(
() => (
<SearchFilterPageFooterButtons
applyChanges={applyChanges}
resetChanges={resetChanges}
/>
),
[resetChanges, applyChanges],
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❌ PERF-6 (docs)

The footerContent JSX should be wrapped in useMemo to prevent unnecessary re-renders. Without memoization, a new JSX element is created on every render, causing React to treat it as a new prop value even when the underlying functions (applyChanges and resetChanges) haven't changed.

Suggested fix:

const footerContent = useMemo(
    () => (
        <SearchFilterPageFooterButtons
            applyChanges={applyChanges}
            resetChanges={resetChanges}
        />
    ),
    [resetChanges, applyChanges],
);

Please rate this suggestion with 👍 or 👎 to help us improve! Reactions are used to monitor reviewer efficiency.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AFAIK this component can be compiled by React Compiler so the useMemo is not needed

const footerContent = (
<SearchFilterPageFooterButtons
applyChanges={applyChanges}
resetChanges={resetChanges}
/>
);

const textInputOptions = {
value: searchTerm,
label: translate('common.search'),
onChangeText: setSearchTerm,
headerMessage: noResultsFound ? translate('common.noResultsFound') : undefined,
};

return (
<SelectionList
sections={sections}
initiallyFocusedOptionKey={initiallySelectedItem?.value}
textInputValue={searchTerm}
onChangeText={setSearchTerm}
textInputLabel={shouldShowTextInput ? translate('common.search') : undefined}
onSelectRow={onSelectItem}
headerMessage={noResultsFound ? translate('common.noResultsFound') : undefined}
ListItem={SingleSelectListItem}
initiallyFocusedItemKey={initiallySelectedItem?.value}
shouldShowTextInput={shouldShowTextInput}
textInputOptions={textInputOptions}
footerContent={shouldAutoSave ? undefined : footerContent}
shouldStopPropagation
showLoadingPlaceholder={!noResultsFound}
shouldShowTooltips
ListItem={SingleSelectListItem}
shouldUpdateFocusedIndex
shouldStopPropagation

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This migration from the old SectionList-based SelectionListWithSections to the new FlashList-based one missed adding disableMaintainingScrollPosition. The new BaseSelectionListWithSections defaults disableMaintainingScrollPosition to false, which means FlashList's maintainVisibleContentPosition is enabled. It caused this bug where searching for a term (e.g. "Travel") filters the list to a few items, and then clearing the search doesn't show the full list because FlashList tries to maintain the scroll position from the filtered view. Fixed in #81294.

/>
);
}
Expand Down
Loading