Skip to content

Avoid full transaction collection scans in useRecentlyAddedData - #97783

Merged
rlinoz merged 3 commits into
Expensify:mainfrom
callstack-internal:perf/recently-added-collection-scans
Aug 5, 2026
Merged

Avoid full transaction collection scans in useRecentlyAddedData#97783
rlinoz merged 3 commits into
Expensify:mainfrom
callstack-internal:perf/recently-added-collection-scans

Conversation

@TMisiukiewicz

@TMisiukiewicz TMisiukiewicz commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

Explanation of Change

Performance fix for the Home Recently added slot. Profiling showed useRecentlyAddedData spending between 50 and 200ms, mostly due to repeatedly scanning the entire transactions_ Onyx collection (~46k entries on large customer account) to resolve data for only ~26 snapshot transactions.

The fix moves the pending-ADD filtering into a useOnyx selector, replaces the transactionID -> transaction Map build with direct transactions_<id> lookups, and resolves unconfirmed rows by key instead of filtering the whole collection.

Since selector work now happens at the subscription layer and useOnyx deep-equal compares selector output, unchanged pending transactions no longer trigger recomputations.

Performance improvement: useRecentlyAddedData drops from ~200ms to ~1ms when switching between reports on a customer account.

Fixed Issues

$ #97784
PROPOSAL:

Tests

  1. Open the Home screen
  2. Go to inbox
  3. Create an expense in any of the reports
  4. Go back to Homescreen
  5. Verify the expense is visible in "Recently added" section
  • 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 verified there are no new alerts related to the canBeMissing param for useOnyx
  • 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
Screen.Recording.2026-08-04.at.13.27.03.mov

@TMisiukiewicz
TMisiukiewicz marked this pull request as ready for review August 4, 2026 11:40
@TMisiukiewicz
TMisiukiewicz requested review from a team as code owners August 4, 2026 11:40
@melvin-bot
melvin-bot Bot requested review from flaviadefaria and mkhutornyi and removed request for a team August 4, 2026 11:40
@melvin-bot

melvin-bot Bot commented Aug 4, 2026

Copy link
Copy Markdown

@mkhutornyi 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 August 4, 2026 11:40
}
return map;
}, [localTransactions]);
const [pendingAddTransactions] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION, {selector: pendingAddTransactionsSelector});

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-11 (docs)

This selector filters the entire TRANSACTION collection (described in the code as holding "tens of thousands of entries") into a Transaction[] of full transaction objects. When a useOnyx subscription uses a selector, Onyx runs deepEqual on the selector output on every collection update to decide whether to re-render. Because the output is a large array of full Transaction objects, that deepEqual is expensive and runs on every unrelated change to the collection — this is exactly the "selector filters/maps a collection into an array" anti-pattern, made worse by returning whole objects rather than a narrowed result. It does not actually save the per-render scan the comment claims, since the scan cost simply moves to per-update.

Downstream the result is only used for its IDs (pendingAddTransactions.map((transaction) => transaction.transactionID)). Since localTransactions is already subscribed to (by key), drop the selector and derive the pending-add IDs inline inside the existing useMemo, as the previous code did:

const [localTransactions] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION);
// ...inside the useMemo:
const pendingAddIDs = Object.values(localTransactions ?? {})
    .filter((transaction) => transaction?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD)
    .map((transaction) => transaction?.transactionID);

This keeps the cheap shallowEqual on the raw localTransactions reference and avoids a redundant second subscription plus the costly deepEqual on a large array output.


Reviewed at: 409adef | 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.

Because the output is a large array of full Transaction objects

it filters only pendingAction === 'ADD' and that's a handful of not-yet synced optimistic creates.

I think it might be a good candidate to improve the PERF-11 rule, as per docs it should not flag such cases:

The selector meaningfully reduces a large dataset to a small result (e.g., a primitive or a few items) by iterating over the subscribed collection itself — the deepEqual cost on a small result is negligible
cc @kacper-mikolajczak

@kacper-mikolajczak kacper-mikolajczak Aug 4, 2026

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.

Hi @TMisiukiewicz thanks for reporting this!

Correct me if I am wrong but it seems like reviewer has a point - wouldn't narrowing down results of the selector to pendingAddIDs directly yield even greater optimisation?

Apart from that, other parts seem to be all good - I wonder if when we'd specified selector to return pendingAddIDs directly, the reviewer would treat it as no-violation.

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.

Correct me if I am wrong but it seems like reviewer has a point - wouldn't narrowing down results of the selector to pendingAddIDs directly yield even greater optimisation?

yeah that part is correct, I addressed that. However I think the output here was already reduced to a small and cheap result, so IMO it should not flag it 🤔 At the same time I know that it's difficult for the agent to define how big will be the output of the selector

@kacper-mikolajczak kacper-mikolajczak Aug 5, 2026

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.

That's correct, the reviewer can only guesstimate how heavy the data selection is and in this particular example the rule was kind of "extended" to make a remark on selector that could be narrowed down - let's see if reviewer flags it now after applying the change.

@mkhutornyi

mkhutornyi commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

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 that the composer does not automatically focus or open the keyboard on mobile unless explicitly intended. This includes checking that returning the app from the background does not unexpectedly open the keyboard.
  • 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 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 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)
  • 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)
  • 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.
  • For any bug fix or new feature in this PR, I verified that sufficient unit tests are included to prevent regressions in this 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.
  • I have checked off every checkbox in the PR reviewer checklist, including those that don't apply to this PR.

Screenshots/Videos

Android: HybridApp
Screen.Recording.2026-08-04.at.4.06.53.PM.mov
Android: mWeb Chrome
iOS: HybridApp
Screen.Recording.2026-08-04.at.4.07.30.PM.mov
iOS: mWeb Safari
MacOS: Chrome / Safari
web.mov

Comment on lines +54 to +56
/** Selecting inside the subscription scans the (very large) collection once per update rather than once per render. */
const pendingAddTransactionsSelector = (transactions: OnyxCollection<Transaction>): Transaction[] =>
Object.values(transactions ?? {}).filter((transaction): transaction is Transaction => transaction?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD);

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.

Same feedback as here: the selector over-returns, defeating its own purpose

const pendingAddTransactionIDsSelector = (transactions: OnyxCollection<Transaction>): string[] =>
    Object.values(transactions ?? {})
        .filter((transaction) => transaction?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD)
        .map((transaction) => transaction.transactionID);

If this doesn't help performance gain much, leave as is.
Not blocker.

@melvin-bot
melvin-bot Bot requested a review from rlinoz August 4, 2026 15:11
rlinoz
rlinoz previously approved these changes Aug 4, 2026

@rlinoz rlinoz left a comment

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.

@TMisiukiewicz

Copy link
Copy Markdown
Contributor Author

addressed to make it cleaner 👍

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: da8eb8a588

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@MelvinBot

Copy link
Copy Markdown
Contributor

🤖 Reviewed — this is a clean, behavior-preserving refactor and the performance win is real. LGTM. All CI is green (ESLint, typecheck, React Compiler Compliance, and the dedicated unit + UI test suites), and I confirmed on web that the Home screen and "Recently added" section still render without errors.

The core of the change — dropping the three full Object.values(transactions_) scans (the Map build + the two inline filter/reduce passes) in favor of keyed transactions_<id> lookups over just the ~26 unconfirmed IDs — is equivalent to the old logic. Resolving combined rows by key rather than reusing the selector's pendingAddTransactionIDs correctly preserves the "sync cleared pendingAction but the ID is still held in unconfirmedTransactionIDs" case, which the existing tests exercise (useRecentlyAddedDataTest.ts:264). The key derivation is also safe: the collection is keyed by transactions_<transactionID>, matching what the removed Map used as its key.

One nit on the framing, not a blocker: the description says "unchanged pending transactions no longer trigger recomputations," but localTransactions is still subscribed without a selector and is still a dependency of the useMemo, so the memo does still recompute on every transactions_ merge. The deep-equal on the selector only stabilizes pendingAddTransactionIDs. The actual win is that each recompute is now O(pending IDs) keyed lookups instead of O(collection) scans — which is exactly where the 200ms → 1ms comes from. Worth tweaking the PR description so a future reader doesn't expect recomputations to be skipped.

Verification details
  • CI: the only non-passing check is Check independent approval (the human-approval gate), not a code failure. ESLint, typecheck, React Compiler Compliance, Bun tests, and all 8 test shards pass.
  • Test coverage: tests/unit/HomePage/RecentlyAddedSection/useRecentlyAddedDataTest.ts covers the paths this refactor touches — pending-ADD merge, dedup against the snapshot, the held-over-unconfirmed case, split-report drop (both online and offline copies), and offline-edit pending treatment.
  • Live web check: Home loads authenticated and the "Recently added" widget renders its empty state (the test account has no expenses) with no crash / error boundary. Screenshot below. (Raw JS console capture isn't exposed for agent-device --platform web, so "no console errors" is inferred from the absence of any visual failure.)

Home screen showing Recently added section with empty state

Home screen showing Recently added section with empty state

@MelvinBot

Copy link
Copy Markdown
Contributor

🤖 No regressions found. I hunted the two areas where a scan → keyed-lookup refactor typically breaks, and both hold up.

1. The keyed-lookup safety invariant. The refactor replaces "iterate the whole transactions_ collection and match by the object's transactionID" with direct transactions_<transactionID> lookups (useRecentlyAddedData.ts:60). That's only safe if the Onyx key suffix always equals transaction.transactionID. It does, structurally: every writer builds the key from the same object's transactionID (key: transactions_${transaction.transactionID}, value = that transaction), and buildOptimisticTransaction always assigns a non-empty ID (TransactionUtils/index.ts:375). So the dropped transaction.transactionID ?? key.slice(...) fallback was guarding a case that can't occur — no transaction is dropped or mis-resolved.

2. The split-expense edge case (the one the old fallback comment worried about) still works: splitting mutates reportID on the same transactions_<id> key rather than re-keying (SplitTransactionUpdate.ts:1578), and the new keyed reportID === SPLIT_REPORT_ID check (useRecentlyAddedData.ts:182) still drops the orphaned original.

3. Offline edits of a pending row aren't stale. The selector only tracks IDs, but the full localTransactions subscription is retained and sourceTransaction/combined re-read the fresh local copy by key on every merge — so an edit to a still-pending expense (or one whose pendingAction cleared but is still held in unconfirmedTransactionIDs) keeps reflecting the latest values.

Live check: created a manual expense from Home and it appeared correctly in "Recently added" (matching merchant/amount/date), no console errors or layout breakage.

Verification details
  • Invariant (code): confirmed key suffix === value.transactionID at every transactions_ write site (MoneyRequestBuilder.ts, TrackExpense.ts, PerDiem.ts, SendInvoice.ts, UpdateMoneyRequest.ts, MergeTransaction.ts, Card.ts, ImportTransactions.ts, Transaction.ts, ReportUtils.ts), and no optimistic→server ID re-key. The only theoretical divergence — a bare Onyx.merge(transactions_<X>, {pendingAction: ADD}) with no full object — has no corresponding write in the codebase (optimistic ADDs always SET the full transaction).
  • Tests: the dedicated unit suite (tests/unit/HomePage/RecentlyAddedSection/useRecentlyAddedDataTest.ts) covers pending-ADD merge, snapshot dedup, the held-over-unconfirmed transition, split-drop (online + offline copy), and offline-edit pending treatment — all green on this branch, alongside the full CI (ESLint, typecheck, React Compiler Compliance, test shards).
  • Live web: Home "Recently added" empty → created CafeTest cash expense → returned to Home → the row rendered with the correct date/merchant/amount. No JS errors.

Home "Recently added" empty (before)

Home Recently added section empty before creating expense

New expense appears in "Recently added" (after)

New CafeTest expense appears in Recently added

The only follow-up remains the (non-regression) wording nit from my earlier review: the PR description implies recomputations are skipped, but the memo still recomputes on every transactions_ merge via the retained localTransactions dependency — the gain is that each recompute is now O(pending) keyed lookups instead of O(collection) scans.

@rlinoz
rlinoz merged commit 69c2388 into Expensify:main Aug 5, 2026
36 of 37 checks passed
@github-actions

github-actions Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

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

@OSBotify

OSBotify commented Aug 5, 2026

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.

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.

6 participants