Skip to content

refactor: split SearchContext into narrow Query, Results, and Selection providers#91303

Merged
mountiny merged 18 commits into
Expensify:mainfrom
callstack-internal:refactor/split-search-context
May 25, 2026
Merged

refactor: split SearchContext into narrow Query, Results, and Selection providers#91303
mountiny merged 18 commits into
Expensify:mainfrom
callstack-internal:refactor/split-search-context

Conversation

@TMisiukiewicz
Copy link
Copy Markdown
Contributor

@TMisiukiewicz TMisiukiewicz commented May 21, 2026

Explanation of Change

The monolithic SearchContext was serving three unrelated concerns (query state, results/data, and selection state) through a single context object. Any component consuming even one field caused re-renders on all three axes of change.

This refactor splits SearchContext into three narrow providers:

  • SearchQueryProvider — owns query string and filter state
  • SearchResultsProvider — owns results data, loading state, and sort config
  • SearchSelectionProvider — owns selection set and bulk-action state

All 90+ consumers across components, hooks, pages, and tests are migrated to import from the matching narrow hook (useSearchQuery, useSearchResults, useSearchSelection). The old SearchContext shim and its re-exports are removed. A new SearchContextDefinitions.ts file holds shared type definitions to avoid circular imports.

The public API of the Search component is unchanged. Tests are updated to use the new MockSearchContextProvider utility.

Since the PR looks pretty big, I prepared a list of files that are must-review, all the rest is just a swap for one of the three narrow hooks, a spot-check of few is enough:

Architecture — start here (new providers + the split)
These are the heart of the refactor. If these are right, the rest is mostly grep-and-replace.

  • src/components/Search/SearchContextDefinitions.ts — bare context objects + defaults. Extracted to break the circular import between providers and useOnyx.
  • src/components/Search/SearchQueryProvider.tsx — owns currentSearchHash, currentSearchKey, query JSON, shouldResetSearchQuery.
  • src/components/Search/SearchResultsProvider.tsx — owns snapshot/live-data switching (shouldUseLiveData), sortedReportIDs, filter-bar loading.
  • src/components/Search/SearchSelectionProvider.tsx — owns selectedTransactions/selectedReports, contains the atomic useSyncSelectedReports hook and deriveSelectedReports helper.
  • src/components/Search/SearchContext.tsx — thin shim: composes the 3 providers and re-exports the narrow hooks for the public API.
  • src/components/Search/types.ts — adds per-bucket types (SearchQuery/Results/SelectionContextValue + …ActionsValue); keeps SearchStateContextValue & SearchActionsContextValue as composed unions.

Cross-bucket consumer (worth a careful read)

  • src/hooks/useOnyx.ts — only call-site that reads from two buckets at once (SearchQueryContext + SearchResultsContext). Pattern reference for any future cross-bucket consumers.

The orchestrator using all three buckets

  • src/components/Search/index.tsx — heaviest consumer; now calls useSearchQueryContext, useSearchResultsContext, useSearchSelectionContext + their actions separately. Worth checking the imports / dep arrays.

Tests

  • tests/utils/MockSearchContextProvider.tsx (new) — test harness mirroring the new 3-provider tree.
  • tests/unit/Search/useSyncSelectedReportsTest.tsx (new) — covers the atomic-sync behavior.

Fixed Issues

$ #91423
PROPOSAL:

Tests

Search query & results

  1. Open Search from the LHN → verify page loads with default Expenses view.
  2. Type into the search input → verify results filter
  3. Switch tabs/types (Expenses → Reports → Chats → Invoices → Trips) → verify results swap correctly
  4. Click a sort header (e.g. Date) → verify order toggles asc/desc; arrow icon updates
  5. Open Sort by / Sort order popups → verify selection persists, list re-sorts

Filters

  1. Open filters bar → apply a filter (e.g. status, date range) → verify URL/query updates, results refresh
  2. Clear filter → verify list returns to previous state.
  3. Save the current search → verify it appears in saved searches; delete it → verify it disappears

Selection

  1. Toggle checkboxes in the list and verify count updates in toolbar.
  2. Select all in header → verify every visible row checked; Deselect all → cleared.
  3. With items selected, open the bulk actions menu → confirm available actions render (Approve, Pay, Hold, Unhold, Delete, Export, Download PDF, Change Report, Reject, Add/Change Approver, Duplicate).
  4. Switch tabs while items are selected → verify selection clears appropriately (expected behavior).
  • Verify that no errors appear in the JS console

Offline tests

N/A

QA Steps

Same as tests

  • Verify that no errors appear in the JS console

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I followed proper code patterns (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text shown in the product is localized by adding it to src/languages/* files and using the translation method
      • If any non-english text was added/modified, I used JaimeGPT to get English > Spanish translation. I then posted it in #expensify-open-source and it was approved by an internal Expensify engineer. Link to Slack message:
    • I verified all numbers, amounts, dates and phone numbers shown in the product are using the localization methods
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.ts or at the top of the file that uses the constant) are defined as such
  • I verified that if a function's arguments changed that all usages have also been updated correctly
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG))
  • If new assets were added or existing ones were modified, I verified that:
    • The assets are optimized and compressed (for SVG files, run npm run compress-svg)
    • The assets load correctly across all supported platforms.
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • If a new page is added, I verified it's using the ScrollView component to make it scrollable when more elements are added to the page.
  • I added unit tests for any new feature or bug fix in this PR to help automatically prevent regressions in this user flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.

Screenshots/Videos

Android: Native
Android: mWeb Chrome
iOS: Native
iOS: mWeb Safari
MacOS: Chrome / Safari
web.mov

@TMisiukiewicz TMisiukiewicz changed the title refactor: split SearchContext into narrow Query, Results, and Selection providers [HOLD #91188] refactor: split SearchContext into narrow Query, Results, and Selection providers May 22, 2026
@TMisiukiewicz TMisiukiewicz changed the title [HOLD #91188] refactor: split SearchContext into narrow Query, Results, and Selection providers refactor: split SearchContext into narrow Query, Results, and Selection providers May 22, 2026
@codecov
Copy link
Copy Markdown

codecov Bot commented May 22, 2026

Codecov Report

✅ Changes either increased or maintained existing code coverage, great job!

Files with missing lines Coverage Δ
...onents/MoneyRequestReportView/SelectionToolbar.tsx 76.59% <100.00%> (ø)
...c/components/ReportActionItem/MoneyRequestView.tsx 75.61% <100.00%> (ø)
src/components/Search/SearchContext.tsx 100.00% <100.00%> (+44.28%) ⬆️
src/components/Search/SearchContextProvider.tsx 100.00% <100.00%> (ø)
...earch/SearchList/ListItem/ReportListItemHeader.tsx 89.09% <100.00%> (+0.20%) ⬆️
...h/SearchList/ListItem/TransactionGroupListItem.tsx 73.10% <100.00%> (ø)
...ts/Search/SearchPageHeader/useSearchFiltersBar.tsx 18.51% <100.00%> (ø)
src/components/Search/SearchQueryProvider.tsx 100.00% <100.00%> (ø)
...rc/components/Search/SearchRouter/SearchRouter.tsx 46.15% <100.00%> (ø)
src/hooks/useAllTransactions.ts 100.00% <100.00%> (ø)
... and 69 more
... and 9 files with indirect coverage changes

@TMisiukiewicz TMisiukiewicz marked this pull request as ready for review May 22, 2026 12:04
@TMisiukiewicz TMisiukiewicz requested review from a team as code owners May 22, 2026 12:04
@melvin-bot melvin-bot Bot requested review from flaviadefaria and mananjadhav and removed request for a team May 22, 2026 12:04
@melvin-bot
Copy link
Copy Markdown

melvin-bot Bot commented May 22, 2026

@mananjadhav Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button]

@melvin-bot melvin-bot Bot removed the request for review from a team May 22, 2026 12:04
@mountiny mountiny removed the request for review from mananjadhav May 22, 2026 12:09
@mountiny mountiny requested a review from Pujan92 May 22, 2026 12:12
@Pujan92
Copy link
Copy Markdown
Contributor

Pujan92 commented May 22, 2026

Reviewer Checklist

  • I have verified the author checklist is complete (all boxes are checked off).
  • I verified the correct issue is linked in the ### Fixed Issues section above
  • I verified testing steps are clear and they cover the changes made in this PR
    • I verified the steps for local testing are in the Tests section
    • I verified the steps for Staging and/or Production testing are in the QA steps section
    • I verified the steps cover any possible failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
  • I checked that screenshots or videos are included for tests on all platforms
  • I included screenshots or videos for tests on all platforms
  • I verified tests pass on all platforms & I tested again on:
    • Android: HybridApp
    • Android: mWeb Chrome
    • iOS: HybridApp
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • If there are any errors in the console that are unrelated to this PR, I either fixed them (preferred) or linked to where I reported them in Slack
  • I verified proper code patterns were followed (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick).
    • I verified that the left part of a conditional rendering a React component is a boolean and NOT a string, e.g. myBool && <MyComponent />.
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text shown in the product is localized by adding it to src/languages/* files and using the translation method
    • I verified all numbers, amounts, dates and phone numbers shown in the product are using the localization methods
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I verified that this PR follows the guidelines as stated in the Review Guidelines
  • I verified other components that can be impacted by these changes have been tested, and I retested again (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar have been tested & I retested again)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.js or at the top of the file that uses the constant) are defined as such
  • If a new component is created I verified that:
    • A similar component doesn't exist in the codebase
    • All props are defined accurately and each prop has a /** comment above it */
    • The file is named correctly
    • The component has a clear name that is non-ambiguous and the purpose of the component can be inferred from the name alone
    • The only data being stored in the state is data necessary for rendering and nothing else
    • For Class Components, any internal methods passed to components event handlers are bound to this properly so there are no scoping issues (i.e. for onClick={this.submit} the method this.submit should be bound to this in the constructor)
    • Any internal methods bound to this are necessary to be bound (i.e. avoid this.submit = this.submit.bind(this); if this.submit is never passed to a component event handler like onClick)
    • All JSX used for rendering exists in the render method
    • The component has the minimum amount of code necessary for its purpose, and it is broken down into smaller components in order to separate concerns and functions
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG)
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • If a new page is added, I verified it's using the ScrollView component to make it scrollable when more elements are added to the page.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.
  • I have checked off every checkbox in the PR reviewer checklist, including those that don't apply to this PR.


Screenshots/Videos

Android: HybridApp
Android: mWeb Chrome
iOS: HybridApp
Simulator.Screen.Recording.-.iPhone.15.Pro.-.2026-05-22.at.21.30.58.mov
iOS: mWeb Safari
Simulator.Screen.Recording.-.iPhone.15.Pro.-.2026-05-22.at.21.33.09.mov
MacOS: Chrome / Safari
Screen.Recording.2026-05-22.at.19.35.22.mov

Comment thread config/eslint/eslint.seatbelt.tsv Outdated
@Pujan92

This comment was marked as outdated.

@Pujan92
Copy link
Copy Markdown
Contributor

Pujan92 commented May 22, 2026

@MelvinBot review

@MelvinBot
Copy link
Copy Markdown
Contributor

Code Review

Well-structured refactor. The split into three narrow providers (Query, Results, Selection) is a solid approach to reducing unnecessary re-renders. The circular dependency handling via SearchContextDefinitions.ts is well-documented and correctly motivated.

Architecture looks good:

  • Clean provider nesting order (Query → Results → Selection) matches the data dependency chain — Selection and Results both read from Query context
  • The state/actions split into separate contexts per bucket is the right pattern — components that only read state won't re-render when action references change
  • useOnyx.ts correctly uses React.use() with the raw context objects from SearchContextDefinitions.ts, avoiding the circular dep
  • All 70+ external consumers correctly import from SearchContext.tsx (the public surface), not from individual providers
  • useSyncSelectedReports is correctly co-located with SearchSelectionProvider and re-exported through SearchContextProvider

Issues to address:

  1. Duplicate hook definitions — Each hook (useSearchQueryContext, useSearchResultsContext, etc.) is defined in both SearchContext.tsx and its corresponding provider file. The provider-local copies are only used internally by sibling providers (SearchResultsProvider imports useSearchQueryContext from SearchQueryProvider), but the duplication is confusing and creates a maintenance risk — if someone changes one copy, they might miss the other. Consider removing the hook definitions from the provider files and having the internal cross-provider imports also go through SearchContext.tsx or SearchContextDefinitions.ts. If the duplication is intentional for the circular dep reason, a comment explaining this would help.

  2. SearchResultsProvider imports useOnyx directly from react-native-onyx (line 4) — The eslint-disable comment explains this is to avoid circular dependencies, which makes sense since the custom useOnyx hook imports from SearchContext.tsx. However, this means SearchResultsProvider bypasses the snapshot-aware useOnyx wrapper. Is this intentional? If so, worth a brief comment explaining that the provider itself manages the snapshot/live-data switching so it doesn't need the wrapper's logic.

  3. Context value object stability — In SearchQueryProvider, SearchResultsProvider, and SearchSelectionProvider, the state value objects are created inline on every render. Since the whole point of this refactor is to reduce re-renders, consider wrapping these in useMemo so consumers don't re-render when the provider's parent re-renders but none of the context values actually changed. The actions objects (which contain stable callbacks) would especially benefit from memoization.

Minor nits (non-blocking):

  • SearchSelectionProvider.tsx:107selectAllMatchingItems as a state setter name reads like an action, not a boolean state. Consider renaming to setAreAllMatchingItemsSelected for clarity.
  • The SearchContextProvider.tsx composition file is clean and minimal — nice.

Overall this is a well-executed refactor with clear motivation and good test coverage. The main actionable feedback is around memoizing context value objects (point 3) — without that, the re-render reduction benefit is partially lost.

@Pujan92
Copy link
Copy Markdown
Contributor

Pujan92 commented May 24, 2026

Duplicate hook definitions — Each hook (useSearchQueryContext, useSearchResultsContext, etc.) is defined in both SearchContext.tsx and its corresponding provider file. The provider-local copies are only used internally by sibling providers (SearchResultsProvider imports useSearchQueryContext from SearchQueryProvider), but the duplication is confusing and creates a maintenance risk — if someone changes one copy, they might miss the other. Consider removing the hook definitions from the provider files and having the internal cross-provider imports also go through SearchContext.tsx or SearchContextDefinitions.ts. If the duplication is intentional for the circular dep reason, a comment explaining this would help.

I think this point makes sense, we can dedupe the defined hooks from provider files.

…-context

# Conflicts:
#	config/eslint/eslint.seatbelt.tsv
#	src/components/MoneyReportHeaderPrimaryAction/SubmitPrimaryAction.tsx
@TMisiukiewicz
Copy link
Copy Markdown
Contributor Author

  1. Duplicate hook definitions - done - removed definitions from three privder files
  2. Direct useOnyx import in SearchResultsProvider - updated the comment with explanation
  3. React Compiler handles memoization automatically

Copy link
Copy Markdown
Contributor

@Pujan92 Pujan92 left a comment

Choose a reason for hiding this comment

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

LGTM 🚀

@melvin-bot melvin-bot Bot requested a review from mountiny May 25, 2026 08:23
@mountiny mountiny merged commit 759e3d3 into Expensify:main May 25, 2026
40 checks passed
@OSBotify
Copy link
Copy Markdown
Contributor

✋ This PR was not deployed to staging yet because QA is ongoing. It will be automatically deployed to staging after the next production release.

@github-actions
Copy link
Copy Markdown
Contributor

🚧 @mountiny has triggered a test Expensify/App build. You can view the workflow run here.

@OSBotify
Copy link
Copy Markdown
Contributor

🚀 Deployed to staging by https://github.com/mountiny in version: 9.3.81-0 🚀

platform result
🕸 web 🕸 success ✅
🤖 android 🤖 cancelled 🔪
🍎 iOS 🍎 cancelled 🔪

@MelvinBot
Copy link
Copy Markdown
Contributor

After reviewing the changes in this PR, no help site documentation updates are required.

This PR is a pure internal code refactoring that splits SearchContext into three narrower React context providers (SearchQueryProvider, SearchResultsProvider, SearchSelectionProvider) to reduce unnecessary re-renders. There are no changes to user-facing behavior, UI text, feature names, navigation, or functionality — only internal component architecture changes.

@OSBotify
Copy link
Copy Markdown
Contributor

🚀 Deployed to production by https://github.com/luacmartins in version: 9.3.81-2 🚀

platform result
🕸 web 🕸 success ✅
🤖 android 🤖 success ✅
🍎 iOS 🍎 success ✅

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants