Skip to content

[HOLD][No QA] Make bulk-actions hooks React Compiler compliant and perf-clean them#88189

Draft
roryabraham wants to merge 20 commits intomainfrom
Rory-ReactCompilerUseSelectedTransactionsActions
Draft

[HOLD][No QA] Make bulk-actions hooks React Compiler compliant and perf-clean them#88189
roryabraham wants to merge 20 commits intomainfrom
Rory-ReactCompilerUseSelectedTransactionsActions

Conversation

@roryabraham
Copy link
Copy Markdown
Contributor

@roryabraham roryabraham commented Apr 17, 2026

HOLD #79387 (comment)

Explanation of Change

Make useSelectedTransactionsActions and useSearchBulkActions React Compiler-compliant, remove manual memoization, plus targeted perf and dead-code cleanup in the same areas.

Fixed Issues

related to #68765
potentially related to #77171 (comment)

Tests

  1. Open a money-request report with several transactions, enter selection mode, select multiple. Verify the dropdown shows every applicable option (Edit multiple, Hold, Unhold, Reject, Export, Merge, Move expenses, Split, Duplicate, Delete) and clicking each opens the expected flow.
  2. Repeat on Search (Expenses, Reports, Expense Reports data types); verify the same options plus Approve, Change approver, Submit, Pay, and the Undelete shortcut when only deleted transactions are selected.
  3. Bulk Pay: select a payable report on Search → Pay → confirm VBBA vs Elsewhere routing still works (covers the inlined policyIDsWithVBBA path).
  4. Bulk Hold: select a hold-eligible transaction on Search → Hold → confirm the submitter-only vs mixed-ownership modal behaviour (covers the lazy areAllTransactionsFromSubmitter path).
  5. Bulk Duplicate: trigger Duplicate from both the report header and the Search bulk actions; confirm duplicates land in the expected workspace with the expected transaction-draft contents (covers the useAllTransactions search-merge path).
  • Verify that no errors appear in the JS console

Offline tests

  1. Offline + selection: bulk-actions dropdown still renders.
  2. Offline Hold/Unhold in Search: request queues, UI reflects pending state.
  3. Offline Duplicate: dropdown entry still present (hook already subscribes to the Onyx data it needs).

QA Steps

Existing BrowserStack regression cases (App project PR-51):

  • TC-3758 Add Expenses to report

  • TC-3759 Batch moving Expenses to another report

  • TC-3760 Remove Expense from Report

  • TC-3819 Splitting an expense

  • TC-3820 Post-split actions - Revert Split

  • TC-3821 Post-split actions

  • TC-3740 Manual Submission Reports - Open state and Duplicate option

  • TC-5053 Export multiple reports - Custom user CSV and Workspace CSV - Reports tab

  • TC-5054 Export multiple expenses - Custom user CSV and Workspace CSV - Reports tab

  • TC-5057 Export multiple expenses - Custom user CSV and Workspace CSV - Inbox tab

  • TC-177533 Export Report - Bulk Export to QBO and Manual Export States

  • TC-135501 Expense Merge - Cross Report Merging and Duplicate Prevention

  • 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

Replace the duplicateHandlerRef pattern (which reads a ref during render
and bails React Compiler) with a useState slot, strip manual useMemo/
useCallback wrappers now that the compiler can own memoization, and
regroup hooks, state, and handlers for readability.

Made-with: Cursor
Replace the duplicateHandlerRef and onBulkPaySelectedRef patterns
(render-time ref reads that bail React Compiler) with a useState slot
and direct callback return, swap the lastNonEmptySearchResultsRef
fallback for usePreviousDefined, strip manual useMemo/useCallback
wrappers now that the compiler can own memoization, inline the
headerButtonsOptions IIFE into an if/else chain, and regroup hooks,
state, and handlers for readability.

Made-with: Cursor
isDeleteModalVisible, showDeleteModal, and hideDeleteModal were
exported but not consumed: SelectionToolbar passes its own
onDeleteSelected callback and MoneyReportHeader overrides the Delete
option's onSelected with a local showConfirmModal flow. Drop the
useState, both helpers, and the unreachable else branch; collapse the
onSelected to a single optional-chained call. Remove the stale assertions
and the "show and hide delete modal" test case from the unit test.

Made-with: Cursor
useSearchBulkActions:
- Drop unused ShouldShowBulkDuplicateParams type export
- Drop unreachable selectedTransactionReportIDs ?? selectedReportIDs
  fallback (selectedTransactionReportIDs is always a defined array)
- Drop redundant status == null re-check in handleBasicExport (already
  handled by the earlier early return)
- Drop the standalone accountID destructuring and consistently use
  currentUserPersonalDetails?.accountID

Stop re-exporting raw Onyx collections from both hooks. Consumers
(MoneyReportHeader, SelectionToolbar, SearchBulkActionsButton) now
read COLLECTION.TRANSACTION / COLLECTION.REPORT directly and pull
searchData from useSearchStateContext, matching how they already
subscribe to related keys. Updated the duplicate-action unit test
helper to do the same.

Made-with: Cursor
The hooks already subscribe to COLLECTION.TRANSACTION / COLLECTION.REPORT
internally (needed for shouldShowBulkDuplicateOption and other derived
values). Having consumers also subscribe directly creates a duplicate
subscription to the same key on the same fiber without eliminating the
hook-internal one. Go back to returning allTransactions, allReports, and
searchData from the hooks so BulkDuplicateHandler can receive them as
props from a single subscription.

Reverts only the Onyx-reexport portion of 99585ef; the dead-code cleanups
(ShouldShowBulkDuplicateParams, selectedTransactionReportIDs fallback,
status re-check, accountID destructuring) stay.

Made-with: Cursor
The list was built on every render by iterating every workspace policy,
just to answer one O(1) question inside onBulkPaySelected: does this
specific policy have a VBBA? Replace the list + .includes() check with a
direct policy lookup at click time.

Made-with: Cursor
The submitterReports scan walked every key in currentSearchResults.data
on every render just to answer a question that is only asked inside the
hold option's onSelected. Wrap the computation in a thunk that the hold
handler invokes on click, so search pages with thousands of results stop
paying this per render.

Made-with: Cursor
…Actions

The hook previously iterated selectedTransactionIDs three times at the
top of render (build selectedTransactionsList, owner analysis, build
selectedTransactionsForDuplicate) with two redundant allTransactions
lookups per ID. Fold them into a single pass.

Made-with: Cursor
The hook previously iterated Object.values(selectedTransactions) seven
times per render to derive selectedTransactionReportIDs, selectedPolicyIDs,
the selectedBulkCurrency fallback, expenseCount/uniqueReportCount,
isAnyTransactionOnHold, isAllOneTransactionReport, and the
selectedTransactionsList inside the non-all-matching branch. Fold them
into a single Object.entries pass at the top of the hook so each
selected transaction is visited once per render. Event-handler-local
traversals (handleApproveWithDEWCheck, onBulkPaySelected, edit-multiple
onSelected) are unchanged - they only run on click.

Made-with: Cursor
Drop the useMemo wrapper - React Compiler already memoizes this hook.
Replace the Object.keys + filter + reduce + double-spread chain with a
single shallow copy of the Onyx collection followed by one flat loop
that folds in search-only transactions. Behavior is unchanged: Onyx
values still take precedence over search snapshots.

Made-with: Cursor
When the current search result set does not surface any transactions that
aren't already in the Onyx collection, return the Onyx reference directly
instead of eagerly cloning it. The clone still happens when there is
genuinely something to merge, preserving the "Onyx takes precedence"
semantics.

Made-with: Cursor
The bulk-actions hooks cleanup dropped five warnings (via the ref-forwarding
rewrite and the useMemo/useCallback stripping). Sync the cap with the new
count so it catches any regression.

Made-with: Cursor
The previous filter+reduce+double-spread chain always returned a defined
object because of the trailing spread. The defer-copy rewrite lost that
guarantee: when search data is present but contains no transaction
entries and the Onyx collection is also empty, the hook returned
undefined. That broke "useAllTransactions > should handle empty
collection and empty search results". Restore the always-defined return
with a trailing ?? {} in the search-data branch.

Made-with: Cursor
…SelectedTransactionsActions

Made-with: Cursor

# Conflicts:
#	android/app/build.gradle
#	ios/NewExpensify/Info.plist
#	ios/NotificationServiceExtension/Info.plist
#	ios/ShareViewController/Info.plist
#	package-lock.json
#	package.json
#	src/hooks/useSearchBulkActions.ts
#	src/hooks/useSelectedTransactionsActions.ts
#	src/libs/actions/Link.ts
#	src/pages/iou/request/step/IOURequestStepConfirmation.tsx
#	src/pages/iou/request/step/IOURequestStepScan/components/ReceiptPreviews/index.tsx
The merge resolution left a stray blank line that the CI Prettier check
flagged. Apply `npm run prettier` to satisfy the formatter.

Made-with: Cursor
Both came in via a merge commit on this branch and aren't part of this
PR's intent. getAdaptedStateFromPath's Plaid OAuth iOS redirect is
already handled in main by a different code path, and the
Mobile-Expensify submodule hash should track main. Restore both to
origin/main.

Made-with: Cursor
The test helper was passing Object.keys(mockSelectedTransactions) inline
as selectedTransactionsKeys on every render. Because our state-based
duplicate-handler slot updates state (rather than a ref) whenever
setDuplicateHandler is called, an unstable handleDuplicate identity
caused BulkDuplicateHandler's useEffect to re-fire after every render,
in turn triggering another state update and another render - an infinite
loop that CI reports as a Jest worker SIGTERM.

Memoize the keys with an empty-deps useMemo in the test helper; renderHook
spins up a fresh hook instance per test, so there's no cross-test
staleness.

Also decouple the duplicate option's visibility from whether the handler
has been registered yet: keep the option in the dropdown as soon as
isDuplicateOptionVisible is true, falling back to a no-op onSelected
when duplicateHandler is still null. This matches the pre-refactor
behavior where the ref defaulted to () => {} so the option was visible
before BulkDuplicateHandler's useEffect registered the real handler.

Made-with: Cursor
The empty-deps useMemo with a `// eslint-disable-next-line
react-hooks/exhaustive-deps` suppression triggers a React Compiler bail
("skipped optimizing this component because one or more React ESLint
rules were disabled"), which the compliance check flags as a regression
against main.

List mockSelectedTransactions explicitly in the deps array instead.
beforeEach reassigns the module-level `let`, which lets the useMemo
re-memoize across test boundaries; within a single render cycle it stays
stable, so handleDuplicate downstream is still stable. No lint
suppression, no compiler bail.

I confirmed locally that dropping the useMemo entirely and relying on
the React Compiler to auto-memoize doesn't work: the compiler can't
prove the module-level let is stable, so Object.keys(...) is treated as
a new expression each render and we get the same infinite render loop.

Made-with: Cursor
The dep was only there to satisfy the exhaustive-deps lint rule without
a suppression (an empty deps array previously required one, which in turn
tripped React Compiler's bail). The lint rule actually accepts an empty
deps array here since the hook returns a stable value, and an empty deps
array is semantically correct: renderHook tears down the hook between
tests, so we never need the useMemo to recompute within a single instance.

Made-with: Cursor
@melvin-bot
Copy link
Copy Markdown

melvin-bot bot commented Apr 17, 2026

npm has a package.json file and a package-lock.json file. It seems you updated one without the other, which is usually a sign of a mistake. If you are updating a package make sure that you update the version in package.json then run npm install

@roryabraham roryabraham changed the title Make bulk-actions hooks React Compiler compliant and perf-clean them [No QA] Make bulk-actions hooks React Compiler compliant and perf-clean them Apr 17, 2026
@codecov
Copy link
Copy Markdown

codecov bot commented Apr 17, 2026

Codecov Report

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

Files with missing lines Coverage Δ
src/hooks/useAllTransactions.ts 100.00% <100.00%> (ø)
src/hooks/useSelectedTransactionsActions.ts 82.55% <85.71%> (+6.64%) ⬆️
src/components/Search/BulkDuplicateHandler.tsx 0.00% <0.00%> (ø)
src/hooks/useSearchBulkActions.ts 43.33% <41.97%> (+1.15%) ⬆️
... and 54 files with indirect coverage changes

…loop

On the money-request report header path, opening selection mode and
selecting multiple transactions reliably reproduced "Maximum update
depth exceeded". MoneyReportHeader carries a
react-hooks/exhaustive-deps suppression (around clearSelectedTransactions,
unrelated to this PR) that causes React Compiler to skip the whole
component. Without compiler memoization, the inline
`onAfterDuplicate={() => clearSelectedTransactions(true)}` prop to
BulkDuplicateHandler churns each render, which in turn churns
handleDuplicate inside useBulkDuplicateAction, which refires
BulkDuplicateHandler's onHandlerReady effect, which drives
useSelectedTransactionsActions' setDuplicateHandler state into a loop.

Stop handing the parent the raw handleDuplicate. Keep the latest handler
in a ref (updated in useInsertionEffect so callers always see the latest
at call time) and expose a useCallback-stable invoker to the parent via
onHandlerReady. The effect now depends only on that stable invoker and
runs once per mount, regardless of whether props from upstream
components are memoized or not.

Made-with: Cursor
@roryabraham
Copy link
Copy Markdown
Contributor Author

Ugh, I kind of hit an impasse with this because fundamentally the data flow that was causing the Rule of React violations was wrong:

  1. MoneyReportHeaderContent uses useSelectedTransactionsActions to build the option list for selected transaction actions.
  2. useSelectedTransactionActions owns the duplicateHandler state and uses it for the Duplicate action (created in render). It also exposes setDuplicateHandler to the parent MoneyReportHeaderContent.
  3. Creating the duplicate handler is expensive due to the many subscriptions needed. When it's needed, we want it to be reactive to its subscriptions, but when it's not needed we don't want the subscriptions.
  4. So we delegate the creation of the duplicate handler to BulkDuplicateHandler, a bastion component that we render conditionally and which owns the subscriptions needed to create the delegate handler. It receives an onHandlerReady prop which would be more aptly named registerDuplicateHandler.
  5. MoneyReportHeaderContent passes setDuplicateHandler (the setter created in useSelectedTransactionActions) to BulkDuplicateHandler.
  6. This pattern is reused in 3 places: MoneyReportHeaderContent, SelectionToolbar, and SearchBulkActionsButton.

So here are my thoughts:

  1. In each of these cases the duplicateHandler state is owned in the wrong place. It should live in the parent, and useSelectedTransactionActions should just take the duplicateHandler as a prop. That's an improvement but insufficient to resolve the code smells to me.
  2. If we do 1, then still, fundamentally state that is owned by the parent and set by the child breaks the canonical data flow of React. This is the source of all our tension here.

So what options do we have to address this? I see a few options, but of all of the options available, this seems the best/most correct...

Move the consumer down, rather than the data up. Currently our mental model is something like: MoneyReportHeader needs handleDuplicates → child creates it → child hands it up -> MoneyReportHeader passes it to ButtonWithDropdownMenu.

If ButtonWithDropdownMenu was composable via JSX rather than with an options array:

<ButtonWithDropdownMenu>
    {isDuplicateOptionVisible && <DuplicateAction />}
    ...
    // other actions in the dropdown menu are their own React components
</ButtonWithDropdownMenu>

Then <DuplicateAction> can own the subscriptions it needs, while still being rendered conditionally. top-down data flow restored. children own their subscriptions and can be rendered conditionally.


But that's a big, big refactor that needs to start at the lowest level and work its way up. Fortunately, a decomposition of ButtonWithDropdownMenu is already proposed here. So I'm going to put this on HOLD for that.

@roryabraham roryabraham changed the title [No QA] Make bulk-actions hooks React Compiler compliant and perf-clean them [HOLD][No QA] Make bulk-actions hooks React Compiler compliant and perf-clean them Apr 17, 2026
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.

1 participant