Skip to content

refactor: remove todos derived value - #94677

Merged
mountiny merged 23 commits into
Expensify:mainfrom
callstack-internal:perf/remove-todos-derived-value
Jun 29, 2026
Merged

refactor: remove todos derived value#94677
mountiny merged 23 commits into
Expensify:mainfrom
callstack-internal:perf/remove-todos-derived-value

Conversation

@TMisiukiewicz

@TMisiukiewicz TMisiukiewicz commented Jun 26, 2026

Copy link
Copy Markdown
Contributor

Explanation of Change

Performance optimization that scopes the to-do computation to the places that actually need it.

The problem: the TODOS derived value runs outside the React lifecycle. Because it's a derived value, it recomputes on any dependency change (reports, transactions, report actions, policies, etc.) regardless of whether anything currently needs the result. That means the expensive to-do classification (createTodosReportsAndTransactions) runs constantly in the background — even when no screen is displaying the counts.

The fix: move the computation into the React lifecycle via the useTodoCounts hook, so it only runs while a consumer is actually mounted, and then further scope it to consumers that are actually focused:

  • Added an optional enabled = true parameter to the useTodoCounts hook (src/hooks/useTodoCounts.ts). When enabled is false, the hook freezes: it skips the expensive classification and returns the last captured result. The cache uses useState + a content-signature-guarded setState during render (the repo's React-Compiler-safe freeze pattern, same as useFrozenPreSelection) — no refs, so it passes the React Compiler compliance check.
  • src/pages/Search/SearchTypeMenuNarrow.tsx: now calls useTodoCounts(useIsFocused()), so to-do counts stop recomputing on background Onyx writes while the Search screen is unfocused, and recompute once on refocus (only if the underlying Onyx data actually changed — otherwise React Compiler memoization yields a cache hit).
  • src/pages/home/ForYouSection/index.tsx: same treatment — useTodoCounts(useIsFocused()) so the home "For You" section freezes its to-do classification when Home is unfocused.

SearchTypeMenuWide (rendered as the search sidebar's ExtraContent) was intentionally left unchanged, because useIsFocused() likely doesn't toggle in that navigator-chrome slot and react-freeze already covers the away-from-Search case.

Fixed Issues

$ #94686
PROPOSAL: N/A

Tests

Setup: Use an account with expense reports across all to-do buckets — at least one report each that you can submit, approve, pay, and export (export requires a workspace with a connected accounting integration where you're the exporter). Have several reports in some buckets and exactly one in another so single-report behavior can be verified.

  1. Open the app
  2. Verify you have reports to submit/approve/pay in "For you" section in Home tab
  3. Go to Spends tab
  4. Verify the numbers in the menu badges match the numbers from "For you" section
  5. Go to Drafts section
  6. Open first report
  7. Submit the report
  8. Go back
  9. Verify the number of drafts was reduced by 1 and Needs approval number increased by 1 (unless it shows 50+)
  10. Go to Needs approval or Ready to pay
  11. Long press on the expense (mobile) and select it with checkbox or select it witch checkbox directly (web)
  12. Use button on top to approve/pay
  13. Verify the number in the badge was reduced by 1
  14. Go to Home again
  15. Verify the numbers from the badges are the same as in "For you"
  • 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
    • 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 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
Simulator.Screen.Recording.-.iPhone.17.Pro.-.2026-06-29.at.12.01.05.mov
iOS: mWeb Safari
MacOS: Chrome / Safari
Screen.Recording.2026-06-29.at.12.09.14.mov

@TMisiukiewicz TMisiukiewicz changed the title Freeze useTodoCounts for unfocused screens refactor: remove todos derived value Jun 26, 2026
@TMisiukiewicz
TMisiukiewicz force-pushed the perf/remove-todos-derived-value branch from ce8eb96 to e681dbb Compare June 26, 2026 13:02
@codecov

codecov Bot commented Jun 26, 2026

Copy link
Copy Markdown

Codecov Report

❌ Looks like you've decreased code coverage for some files. Please write tests to increase, or at least maintain, the existing level of code coverage. See our documentation here for how to interpret this table.

Files with missing lines Coverage Δ
src/CONST/index.ts 94.02% <ø> (-0.05%) ⬇️
src/ONYXKEYS.ts 100.00% <ø> (ø)
src/hooks/useTodoCounts.ts 100.00% <100.00%> (ø)
...rc/libs/actions/OnyxDerived/ONYX_DERIVED_VALUES.ts 100.00% <ø> (ø)
...c/pages/DynamicNewReportWorkspaceSelectionPage.tsx 85.56% <100.00%> (ø)
src/pages/Search/SearchTypeMenuNarrow.tsx 75.86% <100.00%> (+0.28%) ⬆️
src/pages/home/ForYouSection/index.tsx 100.00% <100.00%> (ø)
src/selectors/Todos.ts 100.00% <ø> (ø)
src/components/Search/SearchResultsProvider.tsx 69.23% <50.00%> (ø)
src/pages/Search/SearchTypeMenuWide.tsx 0.00% <0.00%> (ø)
... and 2 more
... and 11 files with indirect coverage changes

@TMisiukiewicz
TMisiukiewicz force-pushed the perf/remove-todos-derived-value branch from 9825299 to 9aa3af6 Compare June 26, 2026 14:13
@TMisiukiewicz
TMisiukiewicz marked this pull request as ready for review June 29, 2026 10:21
@TMisiukiewicz
TMisiukiewicz requested review from a team as code owners June 29, 2026 10:21
@melvin-bot
melvin-bot Bot requested review from ZhenjaHorbach and trjExpensify and removed request for a team June 29, 2026 10:21
@melvin-bot

melvin-bot Bot commented Jun 29, 2026

Copy link
Copy Markdown

@ZhenjaHorbach 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]

Comment thread src/pages/Search/SearchTypeMenuWide.tsx
@github-actions

This comment has been minimized.

@ZhenjaHorbach

ZhenjaHorbach commented Jun 29, 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
2026-06-29.14.23.55.mov
Android: mWeb Chrome
2026-06-29.14.18.53.mov
iOS: HybridApp
2026-06-29.14.23.55.mov
iOS: mWeb Safari
2026-06-29.14.18.53.mov
MacOS: Chrome / Safari
2026-06-29.14.10.44.mov

@melvin-bot
melvin-bot Bot requested a review from mountiny June 29, 2026 12:42
@TMisiukiewicz
TMisiukiewicz force-pushed the perf/remove-todos-derived-value branch from 72ed329 to 9c9c1ba Compare June 29, 2026 12:44
Comment thread src/libs/TodosUtils.ts
Comment thread src/libs/TodosUtils.ts
Comment thread src/libs/TodosUtils.ts
@mountiny

Copy link
Copy Markdown
Contributor

@codex review

@mountiny

Copy link
Copy Markdown
Contributor

@MelvinBot Review

mountiny
mountiny previously approved these changes Jun 29, 2026
@MelvinBot

Copy link
Copy Markdown
Contributor

Review

Verdict: Solid, well-reasoned change. The core idea — replacing the always-on TODOS derived value with on-demand hooks scoped to mounted/focused consumers — is sound, the freeze pattern is React-Compiler-safe, and reportMatchesTodoBucket as a single source of truth keeps the classification rules from drifting between the count and search-results paths. Test coverage migrated cleanly (new useTodoCountsTest.tsx covers the freeze behavior). No blocking issues found — a few things worth confirming below.

Worth confirming

1. singleReportIDs referential stability now depends entirely on React Compiler. The deleted todosSingleReportIDsSelector had explicit manual memoization, with a comment stating it was needed because singleReportIDs is consumed as a whole object in ForYouSection's todoItems useMemo dependency array (ForYouSection/index.tsx:144). The new useTodoCounts returns a fresh singleReportIDs object literal on every non-frozen render — the useState freeze only covers the enabled === false case. While focused, stability relies solely on RC memoizing the object based on the (unchanged) bucket lengths/IDs. RC is enabled with no opt-out on these files, so it should hold, but please double-check that on a Home re-render where the underlying Onyx data is unchanged, todoItems does not rebuild (and the classification doesn't re-run). That's the one spot where losing the explicit memo could regress if the compiler ever bails on the component.

2. useTodoCounts(false) still runs the full classification once when it mounts already-disabled (useTodoCounts.ts:48frozen is null on first render, so the early return is skipped). Minor (one extra computation, then it freezes), just noting it.

Other notes (non-blocking)
  • SearchTypeMenuWide left always-enabled — agree with the reasoning, and the inline comment is clear. It lives in the search navigator's ExtraContent (SearchSidebar), which react-freeze suspends when away from Search, so it's already scoped and useIsFocused() wouldn't toggle reliably there.

  • DynamicNewReportWorkspaceSelectionPage dropped the useMemo wrapping policyIDsWithEmptyReportsSelector / buildTransactionsByReportID(allTransactions). Consistent (the input is now a fresh object so the old memo would have been a no-op anyway) and RC should memoize both — same RC-dependency caveat as Some initial fixes and code style updates #1 if the compiler ever bails on this component.

  • Logic parity verified: the four predicates in reportMatchesTodoBucket match the deleted configs/todos.ts exactly, including the !allExpensesHeld / hasOnlyNonReimbursableTransactions / policy?.exporter === login guards. No remaining references to DERIVED.TODOS, todosReportCountsSelector, or EMPTY_TODOS_REPORT_COUNTS anywhere in src/.

  • Behavioral note for QA: because narrow Search/Home freeze when unfocused, badge counts can be momentarily stale after acting on a report from another tab and only refresh on refocus — which is exactly what test steps 8–9 and 14–15 exercise. Expected, just calling it out.


This is an automated review from MelvinBot — treat it as a second pair of eyes, not a substitute for human review.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d795a8990b

ℹ️ 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".

Comment thread src/hooks/useTodoSearchResults.ts
luacmartins
luacmartins previously approved these changes Jun 29, 2026

@luacmartins luacmartins 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.

LGTM

@TMisiukiewicz
TMisiukiewicz dismissed stale reviews from luacmartins and mountiny via ae9c537 June 29, 2026 14:44
@mountiny
mountiny merged commit ca57618 into Expensify:main Jun 29, 2026
32 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.4.25-0 🚀

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

@OSBotify

OSBotify commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

🚀 Deployed to production by https://github.com/cristipaval in version: 9.4.25-2 🚀

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

Bundle Size Analysis (Sentry):

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.

8 participants