[Due for payment 2026-11-25] [$175] Move the unread indicator onto useOnyx so report updates stop getting slower over a session
Proposal: https://expensify.slack.com/archives/C05LX9D6E07/p1793716152641419
Background
The unread indicator (the tab title on web and the app badge on iOS) counts unread reports after every report update. It runs as a plain module outside React in src/libs/UnreadIndicatorUpdater: it reads its data with Onyx.connectWithoutView and caches the count with its own memoize.
Problem
Every report update creates a new copy of the reports list, so the cache never finds a match. Instead it saves each new copy and never clears the old ones, and on every update it compares the new copy against every copy saved before. The longer the app stays open, the more memory it holds and the slower every report update gets. For heavy users with thousands of reports, each update gets slower all through the day.
Solution
Move the unread logic into a small component that renders nothing and reads its data with useOnyx. React Compiler caches the count and only redoes it when its data changes, so no old copies are kept and no custom cache is needed. The counting itself becomes a pure function, and the module-level Onyx subscriptions, the debounce and the navigation listener go away. The unread count behaves the same for the user.
Results
Heavy test account with 4,061 reports, production web build, 4× CPU slowdown, 200 report updates, same day:
- Today: the unread check costs about 0.9 ms more with every update, with no limit: 26 ms at the start, 187 ms after 200 updates. The whole update goes from 519 ms to 678 ms.
- With the fix: the unread check stays flat at about 14 ms, and the whole update stays at about 510 ms for all 200 updates.
- After 200 updates: 678 ms today vs 508 ms with the fix, 170 ms (25%) less per update. The unread check alone drops from 187 ms to 13 ms (93% less), and the gap keeps growing as the session goes on.
- Averaged over all 200 updates: 590 ms vs 513 ms, 77 ms (13%) less per update.
Issue Owner
Current Issue Owner: @mallenexpensifyUpwork Automation - Do Not Edit
- Upwork Job URL: https://www.upwork.com/jobs/~022117736005990270496
- Upwork Job ID: 2117736005990270496
- Last Price Increase: 2026-11-03
Triggered auto assignment to Contributor-plus team member for initial proposal review - @abdulrahuman5196 (External)
Job added to Upwork: https://www.upwork.com/jobs/~022117736005990270496
Proposal
Please re-state the problem that we are trying to solve in this issue.
The unread indicator (browser tab title on Web and app icon badge on iOS) updates its counts after every report update via src/libs/UnreadIndicatorUpdater. Currently, it runs outside React using Onyx.connectWithoutView module subscriptions and caches calculations with memoize. Because every report update creates a new object reference in Onyx, memoize never hits the cache, accumulates past object references indefinitely without bounds, and compares the new copy against every prior copy. For accounts with thousands of reports, memory consumption balloons and each report update degrades progressively over a session (from ~26ms to 187ms+ per unread check).
What is the root cause of that problem?
- In
src/libs/UnreadIndicatorUpdater/index.ts:- Line 131 wraps
getUnreadReportsForUnreadIndicatorwithmemoize(..., {maxArgs: 3}).memoizedefaults to an unbounded cache storing all seen argument combinations. BecauseallReportsis anOnyxCollection<Report>object that receives a new reference on every Onyx update, cache hits never occur. - The cache retains every previous reports object reference indefinitely, leading to memory growth and linear comparison degradation.
- Line 131 wraps
- The unread computation relies on module-level closures (
allReports,allReportNameValuePairs,allReportActions,allDraftComments,reportAttributesDerived,currentUserAccountID,currentUserLogin,conciergeReportID) maintained by imperativeOnyx.connectWithoutViewcalls, manual debouncing,navigationRef.addListener('state'), andAppStateMonitorlisteners outside React's reactive lifecycle.
What changes do you think we should make in order to solve the problem?
-
Convert
getUnreadReportsForUnreadIndicatorinto a pure function: Insrc/libs/UnreadIndicatorUpdater/index.ts(orgetUnreadReportsForUnreadIndicator.ts):- Refactor
getUnreadReportsForUnreadIndicatorto receive all its data dependencies purely via arguments (with optional defaults for unit test compatibility), eliminating all module-level state:
function getUnreadReportsForUnreadIndicator( reports: OnyxCollection<Report>, currentReportID?: string, draftComment?: string, reportNameValuePairs?: OnyxCollection<ReportNameValuePairs>, reportActions?: OnyxCollection<ReportActions>, reportAttributesDerived?: ReportAttributesDerivedValue['reports'], currentUserLogin?: string, currentUserAccountID?: number, conciergeReportID?: string, ): Report[] { const isOffline = getIsOffline(); return Object.values(reports ?? {}).filter((report) => { const notificationPreference = ReportUtils.getReportNotificationPreference(report); if (ReportUtils.isHiddenForCurrentUser(notificationPreference) || notificationPreference === CONST.REPORT.NOTIFICATION_PREFERENCE.MUTE) { return false; } const nameValuePairs = reportNameValuePairs?.[`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${report?.reportID}`]; const isReportArchived = ReportUtils.isArchivedReport(nameValuePairs); const chatReport = reports?.[`${ONYXKEYS.COLLECTION.REPORT}${report?.chatReportID}`]; const oneTransactionThreadReportID = getOneTransactionThreadReportID(report, chatReport, reportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${report?.reportID}`], isOffline); const oneTransactionThreadReport = reports?.[`${ONYXKEYS.COLLECTION.REPORT}${oneTransactionThreadReportID}`]; const derivedIsEmptyReport = report?.reportID ? reportAttributesDerived?.[report.reportID]?.isEmpty : undefined; if (!ReportUtils.isUnread(report, oneTransactionThreadReport, isReportArchived, derivedIsEmptyReport)) { return false; } return ReportUtils.shouldReportBeInOptionList({ report, chatReport, currentReportId: currentReportID, isDefaultRoomsBetaEnabled: false, doesReportHaveViolations: false, isInFocusMode: false, excludeEmptyChats: false, isReportArchived, draftComment, currentUserLogin: currentUserLogin ?? '', currentUserAccountID: currentUserAccountID ?? CONST.DEFAULT_NUMBER_ID, hasGuidesEmails: ReportUtils.isDefaultRoom(report) ? ReportUtils.hasExpensifyGuidesEmails(Object.keys(report?.participants ?? {}).map(Number), undefined) : false, conciergeReportID, derivedIsEmptyReport, }); }); } - Refactor
-
Create the headless component
src/UnreadIndicatorHandler/index.tsx: Create a component that rendersnull, isolates the Onyx subscriptions usinguseOnyx, and reactively triggersupdateUnread:import {useEffect, useMemo} from 'react'; import useOnyx from '@hooks/useOnyx'; import {useCurrentReportIDState} from '@hooks/useCurrentReportID'; import ONYXKEYS from '@src/ONYXKEYS'; import CONST from '@src/CONST'; import {getUnreadReportsForUnreadIndicator} from '@libs/UnreadIndicatorUpdater'; import updateUnread from '@libs/UnreadIndicatorUpdater/updateUnread'; function UnreadIndicatorHandler() { const [reports] = useOnyx(ONYXKEYS.COLLECTION.REPORT); const [session] = useOnyx(ONYXKEYS.SESSION); const [conciergeReportID] = useOnyx(ONYXKEYS.CONCIERGE_REPORT_ID); const [reportNameValuePairs] = useOnyx(ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS); const [reportActions] = useOnyx(ONYXKEYS.COLLECTION.REPORT_ACTIONS); const [draftComments] = useOnyx(ONYXKEYS.COLLECTION.REPORT_DRAFT_COMMENT); const [reportAttributesDerived] = useOnyx(ONYXKEYS.DERIVED.REPORT_ATTRIBUTES); const {currentReportID} = useCurrentReportIDState(); const currentUserAccountID = session?.accountID ?? CONST.DEFAULT_NUMBER_ID; const currentUserLogin = session?.email ?? ''; const draftComment = currentReportID ? draftComments?.[`${ONYXKEYS.COLLECTION.REPORT_DRAFT_COMMENT}${currentReportID}`] : undefined; const unreadReports = useMemo(() => { return getUnreadReportsForUnreadIndicator( reports, currentReportID, draftComment, reportNameValuePairs, reportActions, reportAttributesDerived?.reports, currentUserLogin, currentUserAccountID, conciergeReportID, ); }, [reports, currentReportID, draftComment, reportNameValuePairs, reportActions, reportAttributesDerived, currentUserLogin, currentUserAccountID, conciergeReportID]); const unreadReportIDs = useMemo(() => { return unreadReports.map((report) => report?.reportID).filter((id): id is string => !!id); }, [unreadReports]); useEffect(() => { updateUnread(unreadReports.length, unreadReportIDs); }, [unreadReports.length, unreadReportIDs]); return null; } export default UnreadIndicatorHandler; -
Preserve Android efficiency via
src/UnreadIndicatorHandler/index.android.tsx:updateUnreadis a no-op on Android. To avoid registering 7 unnecessary collection subscriptions on Android (preserving the existingload.android.tsoptimization), provide:function UnreadIndicatorHandler() { return null; } export default UnreadIndicatorHandler; -
Mount
<UnreadIndicatorHandler />insrc/Expensify.tsx: Mount<UnreadIndicatorHandler />inExpensify.tsxright next to<PriorityModeHandler />and other handlers. BecauseExpensify.tsxis wrapped byCurrentReportIDContextProvider,useCurrentReportIDStateautomatically and reactively re-evaluates the unread count when switching chats. -
Remove obsolete code:
- Remove
loadUnreadIndicatorUpdaterfromsrc/SplashScreenStateContext.tsxand deletesrc/libs/UnreadIndicatorUpdater/load.tsandload.android.ts. - Remove module-level
Onyx.connectWithoutView,memoize,debounce, and the navigation/AppState listeners fromsrc/libs/UnreadIndicatorUpdater/index.ts.
- Remove
What alternative solutions did you explore? (Optional)
- Adding an LRU cache or clearing memoize entries in
src/libs/UnreadIndicatorUpdater/index.ts: Rejected because keeping module-level Onyx subscriptions and custom cache management outside React's tree goes against modern NewDot architectural standards. React Compiler anduseOnyxprovide automatic dependency tracking, memoization, and lifecycle garbage collection without custom memory retention.
Contributor details
Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0105126232377c4c5c
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
Proposal
Please re-state the problem that we are trying to solve in this issue.
The unread indicator (browser tab title on Web and app icon badge on iOS) recalculates unread counts via src/libs/UnreadIndicatorUpdater. Currently running outside React via module-level Onyx.connectWithoutView subscriptions, it caches calculations with memoize(getUnreadReportsForUnreadIndicator, {maxArgs: 3}). Because each report update instantiates a new allReports collection object reference, memoize never hits a matching cache key, indefinitely accumulates references, and iterates over every previously saved copy on each comparison. On accounts with thousands of reports, this causes memory bloat and progressively increases unread check duration from ~26ms to over 187ms over a session.
What is the root cause of that problem?
In src/libs/UnreadIndicatorUpdater/index.ts:
getUnreadReportsForUnreadIndicatoris wrapped withmemoize(..., {maxArgs: 3}).memoizedefaults to an unbounded lookup cache. BecauseallReportsis anOnyxCollection<Report>that receives a new reference identity on every Onyx update, cache lookups always miss while indefinitely retaining previousallReportsobject graphs in memory.- In addition, the updater relies on module-level
Onyx.connectWithoutViewsubscriptions, manualdebounce, andNavigation.getTopmostReportId()polling, which bypasses modern declarative React lifecycle management and garbage collection.
What changes do you think we should make in order to solve the problem?
-
Refactor counting into a pure helper: Keep
getUnreadReportsForUnreadIndicatorinsrc/libs/UnreadIndicatorUpdater/index.ts(or export from a dedicated utility) as a pure function accepting all necessary parameters (reports,currentReportID,draftComment,reportNameValuePairs,reportActions,reportAttributesDerived,currentUserLogin,currentUserAccountID,conciergeReportID). -
Create
<UnreadIndicatorHandler />component: Createsrc/components/UnreadIndicatorHandler/index.tsx:- Use
useOnyxto subscribe declaratively to:ONYXKEYS.COLLECTION.REPORTONYXKEYS.SESSIONONYXKEYS.CONCIERGE_REPORT_IDONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRSONYXKEYS.COLLECTION.REPORT_ACTIONSONYXKEYS.COLLECTION.REPORT_DRAFT_COMMENTONYXKEYS.DERIVED.REPORT_ATTRIBUTES
- Read
currentReportIDreactively usinguseCurrentReportIDState(). - Calculate unread reports using
useMemo(or standard React Compiler auto-memoization):const unreadReports = useMemo(() => { return getUnreadReportsForUnreadIndicator( reports, currentReportID, draftComment, reportNameValuePairs, reportActions, reportAttributesDerived?.reports, currentUserLogin, currentUserAccountID, conciergeReportID, ); }, [reports, currentReportID, draftComment, reportNameValuePairs, reportActions, reportAttributesDerived, currentUserLogin, currentUserAccountID, conciergeReportID]); - In a
useEffecttriggered byunreadReports:useEffect(() => { updateUnread( unreadReports.length, unreadReports.map((report) => report?.reportID).filter((id): id is string => !!id), ); }, [unreadReports]); - Component returns
null.
- Use
-
Android Platform No-op: Implement
src/components/UnreadIndicatorHandler/index.android.tsxreturningnullwith no Onyx subscriptions, preserving the current zero-overhead behavior ofload.android.ts. -
Mount Handler & Clean Up Legacy Subscriptions:
- Mount
<UnreadIndicatorHandler />insrc/Expensify.tsxalongside other application-level handlers. - Remove
loadUnreadIndicatorUpdaterfromsrc/SplashScreenStateContext.tsxand deletesrc/libs/UnreadIndicatorUpdater/load.tsandload.android.ts. - Remove module-level
Onyx.connectWithoutView,memoize, andtriggerUnreadUpdatefromsrc/libs/UnreadIndicatorUpdater/index.ts.
- Mount
What alternative solutions did you explore? (Optional)
- Adding LRU eviction or clearing
memoizecache manually: Rejected because custom caching outside React retains boilerplate and misses out on automatic React 19 / React Compiler dependency tracking and garbage collection.
What automated tests can you add to prevent this from re-occurring?
- Add unit test coverage in
tests/unit/UnreadIndicatorHandlerTest.tsxverifying:updateUnreadis called with the correct unread count and report IDs when reports or active report changes.- Multiple rapid report updates correctly recalculate without memory retention or redundant updates.
- Verify existing tests in
tests/unit/UnreadIndicatorUpdaterTest.tspass with the pure function extraction.
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~01b60d704ba377be83
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
Proposal
Please re-state the problem that we are trying to solve in this issue.
The unread indicator (browser tab title on Web and app icon badge on iOS) updates its count after every report change. Currently, it runs as a plain module outside React in src/libs/UnreadIndicatorUpdater/index.ts using Onyx.connectWithoutView module subscriptions and caches calculations with memoize. Because every report update creates a new immutable collection reference, memoize never hits the cache, accumulates past object references indefinitely, and compares the new copy against every prior copy. For accounts with many reports, memory consumption grows and each report update progressively slows down over a session (from ~26ms to 187ms+ per check).
What is the root cause of that problem?
- In
src/libs/UnreadIndicatorUpdater/index.ts:- Line 131 wraps
getUnreadReportsForUnreadIndicatorwithmemoize(..., {maxArgs: 3}).memoizestores past argument combinations without evicting old entries. SinceallReportsis anOnyxCollection<Report>that receives a new reference on every Onyx mutation, every invocation is a cache miss that adds yet another reference to the cache map. - Over a user session with 200+ report mutations, this causes linear comparison overhead and uncollected memory accumulation.
- Line 131 wraps
- Relying on module-level variables (
allReports,allReportActions,allReportNameValuePairs,currentUserAccountID,conciergeReportID) outside the React component lifecycle requires imperative debouncing (debounce(triggerUnreadUpdate, 200)), manualAppStateMonitorlisteners, and manualnavigationReflisteners.
What changes do you think we should make in order to solve the problem?
-
Extract Pure Calculation Logic into
src/libs/UnreadIndicatorUtils.ts:- Move the counting logic from
src/libs/UnreadIndicatorUpdater/index.tsinto a pure functioncalculateUnreadReportsCount(...)insrc/libs/UnreadIndicatorUtils.ts. - Remove the custom
memoizewrapper entirely.
- Move the counting logic from
-
Create Headless Component
src/components/UnreadIndicatorUpdater.tsx:- Create a headless React component that returns
nulland reads data reactively usinguseOnyx:
import React, {useEffect, useMemo} from 'react'; import useOnyx from '@hooks/useOnyx'; import ONYXKEYS from '@src/ONYXKEYS'; import calculateUnreadReportsCount from '@libs/UnreadIndicatorUtils'; import updateUnread from '@libs/UnreadIndicatorUpdater/updateUnread'; function UnreadIndicatorUpdater() { const [reports] = useOnyx(ONYXKEYS.COLLECTION.REPORT); const [reportNameValuePairs] = useOnyx(ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS); const [reportActions] = useOnyx(ONYXKEYS.COLLECTION.REPORT_ACTIONS); const [session] = useOnyx(ONYXKEYS.SESSION); const [conciergeReportID] = useOnyx(ONYXKEYS.CONCIERGE_REPORT_ID); const [reportAttributes] = useOnyx(ONYXKEYS.DERIVED.REPORT_ATTRIBUTES); const unreadCount = useMemo(() => { return calculateUnreadReportsCount({ reports, reportActions, reportNameValuePairs, reportAttributes, currentUserAccountID: session?.accountID, currentUserLogin: session?.email, conciergeReportID, }); }, [reports, reportActions, reportNameValuePairs, reportAttributes, session?.accountID, session?.email, conciergeReportID]); useEffect(() => { updateUnread(unreadCount); }, [unreadCount]); return null; } export default UnreadIndicatorUpdater;- React Compiler /
useMemonaturally caches the calculation and only re-computes when its actual input collections update. No old collection copies are retained, completely eliminating the memory leak and the progressive slow-down.
- Create a headless React component that returns
-
Mount in
src/App.tsx(orsrc/setup/index.tsx):- Mount
<UnreadIndicatorUpdater />alongside other top-level reactive subscribers (e.g.ActiveWorkspace,ThemeScript). - Clean up
src/libs/UnreadIndicatorUpdater/index.ts: remove allOnyx.connectWithoutViewcalls, thedebouncewrapper, and the navigation/AppState listeners.
- Mount
What alternative solutions did you explore? (Optional)
- Setting
maxArgs: 1or clearingmemoizecache manually: Rejected because module-level state outside React still requires manual debounce and lifecycle listeners, which go against modern NewDot architectural patterns favoring declarativeuseOnyxsubscriptions.
What automated tests can you add to prevent this from re-occurring?
- In
tests/unit/UnreadIndicatorUtilsTest.ts:- Verify
calculateUnreadReportsCountaccurately tallies unread reports across different combinations of reports, actions, and user roles. - Verify that unread counts are zero when all reports are marked read.
- Verify
- In
tests/unit/components/UnreadIndicatorUpdaterTest.tsx:- Verify that mounting
UnreadIndicatorUpdatertriggersupdateUnreadwith the calculated unread count. - Verify that updating an unrelated Onyx key does not trigger unnecessary calls to
updateUnread.
- Verify that mounting
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~015b34e130d9aad41d
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
Proposal — Unread Indicator Performance and Lifecycle Correctness
Issue: [Expensify/App #105827](https://github.com/Expensify/App/issues/105827) Related implementation: [PR #104568](https://github.com/Expensify/App/pull/104568) Contributor: Himanshu Shukla GitHub: [himanshu051116](https://github.com/himanshu051116) Engineering portfolio: [Inside the Builder's Mind](https://github.com/himanshu051116/inside-the-builders-mind)
1. Please re-state the problem that we are trying to solve in this issue.
The unread indicator progressively increases the cost of report updates during long-running sessions, particularly for accounts containing thousands of reports.
The existing implementation uses module-level Onyx subscriptions and an unbounded memoization cache. Because report updates produce new collection references, cached results are rarely reused, while historical references continue accumulating.
PR #104568 addresses this architectural problem by moving the calculation into a React component using useOnyx.
My proposed contribution complements that implementation by addressing potential correctness regressions involving network transitions, application lifecycle events, Concierge-driven refreshes, and callback cleanup.
The objective is to preserve the performance improvement without changing the observable behavior of unread indicators on supported platforms.
2. What is the root cause of the problem?
There are two related concerns.
A. Original performance bottleneck
- The custom memoization cache retains historical report collections.
- New collection references produce repeated cache misses.
- Cache comparisons and retained memory grow over the session.
- Imperative subscriptions require additional coordination outside React.
B. Potential regressions in the React-based replacement
After reviewing PR #104568, I identified the following areas requiring additional validation:
-
Non-reactive network dependency: The calculation reads
getIsOffline()without explicitly tracking network status as a React dependency. Changes in connectivity can affect transaction-thread resolution without necessarily invalidating the cached result. -
Foreground refresh semantics: The foreground listener republishes previously calculated report IDs instead of recomputing the current unread state.
-
Callback lifecycle: The registered Concierge refresh callback is not explicitly cleared during component teardown, potentially retaining a stale closure.
-
Insufficient regression coverage: Existing tests establish basic unread-count changes but do not comprehensively exercise these lifecycle and connectivity scenarios.
These findings represent source-level risks that should be confirmed through targeted tests.
3. What changes do you propose?
I recommend retaining the core architecture of PR #104568 and introducing a focused follow-up improvement.
A. Make network state explicit
Use the existing reactive network hook and pass the offline state directly to the unread calculation. This makes the dependency visible to React and testable independently.
B. Preserve on-demand refresh behavior
Implement a controlled refresh mechanism that recomputes unread eligibility using the latest committed inputs when the application becomes active or Concierge requests a fresh snapshot.
Avoid unnecessary resubscription to application lifecycle events after routine report updates.
C. Ensure complete lifecycle cleanup
Unsubscribe foreground listeners and clear any registered callback during unmount, preventing stale component references from being retained.
D. Expand automated regression testing
Add targeted coverage for:
- Network state transitions affecting unread eligibility.
- Foreground refreshes without an intervening Onyx update.
- Concierge-triggered unread refreshes.
- Listener stability across repeated report updates.
- Callback cleanup after unmount.
- Existing unread-to-read transitions.
E. Verify performance and cross-platform compatibility
Run the existing performance benchmark with a high-volume test account and validate the behavior on web, iOS, Android, and offline/reconnect scenarios.
The original reported benchmark and the proposed improvements should be measured separately to avoid attributing unverified performance gains to this follow-up.
4. What alternative solutions did you consider?
Limiting the custom memoization cache: This may reduce memory growth but retains unnecessary cache management and does not address the underlying imperative architecture.
Removing all refresh callbacks: This simplifies the component but risks losing explicit refresh behavior required by foreground and Concierge workflows.
Using cached IDs for every refresh: This avoids recomputation but may fail to reflect mutable inputs that change independently of Onyx collection references.
Submitting a duplicate implementation: Since PR #104568 already addresses the primary performance defect, a duplicate would provide limited value. A targeted review and coordinated follow-up is the more maintainable approach.
5. Expected outcome
The proposed changes aim to achieve three outcomes:
- Preserve the bounded computation behavior introduced by the React-based implementation.
- Maintain consistent unread indicator behavior across connectivity, navigation, and application lifecycle transitions.
- Improve maintainability through explicit dependencies, reliable cleanup, and reproducible regression tests.
6. Implementation and verification status
A focused follow-up patch and supporting test harness have been prepared against the inspected PR revision.
Patch application and syntax-level checks have been performed. Full-repository Jest, TypeScript, lint, device testing, and production performance validation remain outstanding.
I would be happy to coordinate with the existing PR author and reviewer before proposing upstream changes.
Contributor details
GitHub: https://github.com/himanshu051116 Portfolio: https://github.com/himanshu051116/inside-the-builders-mind Expensify account email: [[email protected]](mailto:[email protected]) Upwork profile: https://www.upwork.com/freelancers/~012dd17e6db13358c4?mp_source=share
📣 @himanshu051116! 📣 Hey, it seems we don’t have your contributor details yet! You'll only have to do this once, and this is how we'll hire you on Upwork. Please follow these steps:
- Make sure you've read and understood the contributing guidelines.
- Get the email address used to login to your Expensify account. If you don't already have an Expensify account, create one here. If you have multiple accounts (e.g. one for testing), please use your main account email.
- Get the link to your Upwork profile. It's necessary because we only pay via Upwork. You can access it by logging in, and then clicking on your name. It'll look like this. If you don't already have an account, sign up for one here.
- Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details.
Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>
⚠️ Invalid email. Please make sure to create an Expensify account with this email first here.
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~012dd17e6db13358c4?mp_source=share
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
@elirangoshen Uh oh! This issue is overdue by 2 days. Don't forget to update your issues!
Proposal
Please re-state the problem that we are trying to solve in this issue
The unread indicator (web tab title / iOS app badge) recalculates after every report update via src/libs/UnreadIndicatorUpdater/index.ts, which runs outside React using module-level Onyx.connectWithoutView subscriptions. Each Onyx report update produces a new object reference for the allReports collection, so the memoize cache around the counting function never hits and grows without bound — keeping every previous reports object reference in memory forever and scanning the whole history on every lookup. Over a long session the per-update cost climbs linearly (benchmark: ~26 ms → 187 ms after 200 updates on a 4,061-report account).
What is the root cause of that problem?
Two compounding defects, both in src/libs/UnreadIndicatorUpdater/index.ts:
1. Unbounded memoize cache (line 133) — the memory leak and linear slowdown
// src/libs/UnreadIndicatorUpdater/index.ts:133
const memoizedGetUnreadReportsForUnreadIndicator = memoize(getUnreadReportsForUnreadIndicator, {maxArgs: 3});
Only maxArgs: 3 is passed; no maxSize is supplied. The memoize default is maxSize: Infinity (src/libs/memoize/const.ts:5) and the default equality comparator is deepEqual (src/libs/memoize/const.ts:7). The cache is ArrayCache (src/libs/memoize/cache/ArrayCache.ts), whose getKeyIndex (lines 22–28) walks the array backward comparing every stored key with deepEqual until it finds a match:
// src/libs/memoize/cache/ArrayCache.ts:22-28
function getKeyIndex(key: K): number {
for (let i = cache.length - 1; i >= 0; i--) {
const cacheItem = cache.at(i)?.at(0);
if (cacheItem && keyComparator(cacheItem as K, key)) {
return i;
}
}
return -1;
}
Because allReports (the first memoization arg) is an OnyxCollection<Report> whose reference identity changes on every Onyx write, deepEqual against each prior copy always fails → every update is a miss → a new [key, value] entry is pushed (ArrayCache.set, line 38) and the cache never shrinks (maxSize === Infinity, so the cache.shift() at line 44 never runs). So over a session: cache.length grows by 1 per update, getKeyIndex does an O(n) deepEqual scan over an ever-growing array of large report maps on every call → the observed linear slowdown (26 ms → 187 ms + memory bloat). The prior proposals correctly identify memoize but none traces the full mechanism: it is maxSize: Infinity (const.ts:5) × deepEqual default (const.ts:7) × ArrayCache.getKeyIndex linear backward scan (ArrayCache.ts:22-28) × new-reference-per-update = O(n²) total work.
2. Hidden correctness bug: the memoized function reads module-level state that is not in its cache key (lines 97–129)
Even though memoize is called with {maxArgs: 3}, the function body reads allReportNameValuePairs (line 97), allReportActions (line 100), reportAttributesDerived (lines 103–104), currentUserLogin (line 122), currentUserAccountID (line 123), and conciergeReportID (line 126) directly from module scope — none of which are part of the 3-arg cache key. So a stale cached entry could be returned if only the currentReportID/draftComment args repeat while these module globals changed. This is why the issue asks to make the function pure: threading all inputs as args (so useMemo's dependency array is correct) is required, not optional — a memoize maxSize cap alone would preserve this latent stale-return bug.
What changes do you think we should make in order to solve the problem?
Follow the issue's prescribed direction: move the logic onto a headless React component reading useOnyx, so React Compiler memoizes the count and only recomputes when its inputs actually change.
-
Extract
getUnreadReportsForUnreadIndicatoras a pure function (src/libs/UnreadIndicatorUpdater/index.tsor a siblinggetUnreadReportsForUnreadIndicator.ts): take all data as explicit arguments —reports,currentReportID,draftComment,reportNameValuePairs,reportActions,reportAttributesDerived,currentUserLogin,currentUserAccountID,conciergeReportID. Remove the module-level closures (lines 20–75) and the directgetIsOffline()read at line 79 — passisOfflinein too (cited as a correctness gap by a prior proposal; agree it should be reactive). This removes latent staleness from root-cause #2. -
Create
src/components/UnreadIndicatorHandler/index.tsx— rendersnull, subscribes viauseOnyxto the 7 keys currently held in module scope (ONYXKEYS.COLLECTION.REPORT,ONYXKEYS.SESSION,ONYXKEYS.CONCIERGE_REPORT_ID,ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS,ONYXKEYS.COLLECTION.REPORT_ACTIONS,ONYXKEYS.COLLECTION.REPORT_DRAFT_COMMENT,ONYXKEYS.DERIVED.REPORT_ATTRIBUTES), readscurrentReportID+isOfflinereactively, computesunreadReportsinuseMemo, and callsupdateUnread(unreadReports.length, unreadReportIDs)in auseEffect. React Compiler auto-memoizes; no custom cache, no retained old copies, no O(n) scan. Provideindex.android.tsxreturningnullto preserve the existingload.android.tszero-overhead-on-Android behavior (updateUnreadis a no-op on Android). -
Mount
<UnreadIndicatorHandler />insrc/Expensify.tsxnext to<PriorityModeHandler />, insideCurrentReportIDContextProvidersouseCurrentReportIDStatereacts to chat switches. -
Remove the legacy wiring: delete
memoize(line 133), thedebounce(triggerUnreadUpdate, ...)(lines 140–150),setUnreadUpdateCallback(line 152), the report collectionconnectWithoutView(lines 155–161),navigationRef.addListener('state', …)(lines 163–165),AppStateMonitor.addBecameActiveListener(lines 168–170), andsrc/libs/UnreadIndicatorUpdater/load.ts+load.android.ts; removeloadUnreadIndicatorUpdaterfromsrc/SplashScreenStateContext.tsx.
Why this beats a minimal maxSize fix: capping maxSize would stop the unbounded growth (root cause #1) but leaves root-cause #2 (stale returns from undocumented side-reads) and keeps the imperative, non-reactive architecture the issue explicitly asks to retire.
What specific scenarios should be covered by automated tests?
tests/unit/UnreadIndicatorHandlerTest.tsx:updateUnreadreceives the correct count + reportIDs when reports change.- Updating an unrelated Onyx key does not recompute / re-call
updateUnread. - Switching
currentReportIDupdates the count (draft on the open report no longer counts). - Repeated rapid updates do not accumulate retained references (assert no growth in
Onyxconnection count).
tests/unit/UnreadIndicatorUpdaterTest.ts(existing): pure-function extraction keeps read → unread, mute → excluded, hidden → excluded behavior.- Performance: extend the existing benchmark to assert the per-update unread cost stays flat across 200 updates.
What alternative solutions did you explore? (Optional)
- Cap
memoizemaxSize, e.g.{maxArgs: 3, maxSize: 1}. Stops the leak but keeps the imperative module subscriptions, the debounce, and the side-read staleness bug (#2). The issue explicitly asks for theuseOnyxmigration, so this is a smaller fix than requested. - Switch the equality comparator to
shallow. Reference identity of the top-level collection object still changes per update, so this does not change cache-miss behavior; it would just make a hit (if it ever occurred) cheaper. Does not address growth.
PR
PR will be linked here once created.
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~01b6a593fd295a20bf
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
Proposal
Please re-state the problem that we are trying to solve in this issue.
Over the course of a long app session, report updates get progressively slower and retain more memory because the unread indicator updater relies on Onyx.connectWithoutView and an ineffective memoize wrapper over allReports.
What is the root cause of that problem?
In src/libs/UnreadIndicatorUpdater/index.ts (lines 20–131):
getUnreadReportsForUnreadIndicatoris wrapped inmemoize(..., {monitoringName: 'getUnreadReportsForUnreadIndicator', maxArgs: 3}). BecauseallReports(OnyxCollection<Report>) receives a new top-level object reference on every single report update in Onyx, the memoization cache misses on nearly every call while retaining references to previousallReportscollections in memory.- The module uses
Onyx.connectWithoutView(deprecated in favor ofuseOnyx) to maintain module-levelallReports,currentReportID, andnotificationPreferencestate and runstriggerUnreadUpdateimperatively on every Onyx update.
What changes do you think we should make in order to solve the problem?
- In
src/libs/UnreadIndicatorUpdater/index.ts:- Remove the
memoizewrapper aroundgetUnreadReportsForUnreadIndicatorand makegetUnreadReportsForUnreadIndicator(allReports, currentReportID, allReportNameValuePairs)a pure function. - Remove the
Onyx.connectWithoutViewsubscriptions and module-level mutable state (allReports,allReportNameValuePairs).
- Remove the
- Create a hook
useUnreadIndicatorUpdaterinsrc/libs/UnreadIndicatorUpdater/useUnreadIndicatorUpdater.ts(or a lightweight headless component mounted insrc/Expensify.tsx/NavigationRoot.tsx) that usesuseOnyx(ONYXKEYS.COLLECTION.REPORT)anduseOnyx(ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS)(or a combined selector calculating the unread count directly inside theuseOnyxselector) and callsupdateUnread(totalCount)inside auseEffectwhenever the unread count or current report ID changes. - Update
src/libs/Navigation/NavigationRoot.tsxandtests/unit/UnreadIndicatorUpdaterTest.tsto testgetUnreadReportsForUnreadIndicatorand the newuseOnyx-based updater withoutOnyx.connectWithoutView.
What alternative solutions did you explore? (Optional)
We considered reducing the cache size of memoize to 1, but computing the unread count inside a useOnyx selector eliminates both the memoize overhead and the deprecated Onyx.connectWithoutView listeners.
📣 @jeffrey-graham! 📣 Hey, it seems we don’t have your contributor details yet! You'll only have to do this once, and this is how we'll hire you on Upwork. Please follow these steps:
- Make sure you've read and understood the contributing guidelines.
- Get the email address used to login to your Expensify account. If you don't already have an Expensify account, create one here. If you have multiple accounts (e.g. one for testing), please use your main account email.
- Get the link to your Upwork profile. It's necessary because we only pay via Upwork. You can access it by logging in, and then clicking on your name. It'll look like this. If you don't already have an account, sign up for one here.
- Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details.
Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>
Proposal
Please re-state the problem that we are trying to solve in this issue.
The unread indicator updater becomes progressively slower over a user session because UnreadIndicatorUpdater runs outside React using Onyx.connectWithoutView with a broken module-level memoize cache.
What is the root cause of that problem?
In src/libs/UnreadIndicatorUpdater.ts:
UnreadIndicatorUpdaterlistens toONYXKEYS.COLLECTION.REPORTviaOnyx.connectWithoutView. On every single report update, Onyx emits a new reference for the entire reports collection object.- The module's
memoizecache compares the collection by reference (===), so the cache never matches. As a result,UnreadIndicatorUpdaterrecalculates unread counts across all user reports on every keystroke, draft update, and message receipt, causing CPU thrashing and gradual UI degradation over prolonged sessions.
What changes do you think we should make in order to solve the problem?
- Refactor
UnreadIndicatorUpdaterto migrate fromconnectWithoutViewto React context or a dedicated subscriber component usinguseOnyxwith selective selector hooks. - Alternatively, in
UnreadIndicatorUpdater.ts:- Instead of recomputing all reports on every Onyx notification, maintain an incremental unread counter map keyed by
reportID. - Only recalculate the delta when an individual report's
hasUnreadorlastReadTimeactually changes, rather than iterating over the entire reports dictionary on every unrelated write.
- Instead of recomputing all reports on every Onyx notification, maintain an incremental unread counter map keyed by
What alternative solutions did you explore? (Optional)
Deep-comparing the entire reports collection on every update, but deep object comparison across hundreds of reports introduces even more CPU overhead compared to incremental delta tracking.
@elirangoshen 6 days overdue. This is scarier than being forced to listen to Vogon poetry!