Skip to content

[Due for payment 2026-06-18] [$250] [Performance] Cut ReportActionItem re-renders during message send/receive #91394

Closed

Description

@mountiny

Coming from https://expensify.slack.com/archives/C05LX9D6E07/p1779369728592709

Background:

Each opened chat owns a Report subscribed from Onyx and renders one ReportActionItem per row; an active session keeps hundreds mounted. Onyx pushes a fresh top-level Report reference whenever the backend updates routine fields tied to chat activity, which happens on every incoming or sent message. The action list also recomputes per-row metadata when any row is inserted. ReportActionItem is wrapped in an outer PureReportActionItem layer with React.memo, but most of the heavy children inside it now own their own Onyx subscriptions and memoization.

Problem:

When a user has a long chat open and is actively scrolling or composing, if a message is sent or received in that chat, every visible ReportActionItem re-renders unnecessarily, dropping frames and producing visible jank.

Solution:

  1. Add typed getStableReportSelector: a useOnyx selector that returns a Report projection with the fields tied to chat-activity churn stripped (lastMessageText, lastVisibleActionCreated, lastReadTime, lastReadSequenceNumber, lastMentionedTime, lastVisibleActionLastModified, lastMessageHtml, lastActorAccountID, lastActionType). useOnyx compares selector output with deepEqual, so when only stripped fields change, the subscribed component sees the same projection reference and skips re-rendering. Every other Report field is kept, which intentionally minimizes the risk of regressions in downstream consumers that read fields we haven't explicitly profiled.
    This is a deliberate short-term bridge: it stops heartbeat re-renders without rewriting the tree, but the long-term fix is narrower row dependencies (see Follow-ups), not a permanent “stable Report” API.

  2. Replace the per-row index prop with ReportActionIndexContext. The only descendant that reads the index now is ReportActionItemMessageEdit (for scroll-to-index during edit mode), which becomes a context consumer. List mutations no longer cascade index re-renders through every row.

  3. Patch the three actionable-mention whisper components (MentionWhisperContent, ReportMentionWhisperContent, ConfirmWhisperContent), whose resolve handlers read the stripped fields to build a failure-revert payload. Each adds one extra unselected useOnyx subscription to fetch the full report for the resolve call.

  4. Remove the PureReportActionItem wrapper. With chat-activity churn filtered at the source by the selector's deepEqual comparison, and with most heavy children deep in the tree already owning their own Onyx subscriptions and memoization, the wrapper's React.memo layer no longer earns the indirection. Inline its body into ReportActionItem.

Results (ManualSendMessage span):

  • regular test account (4x CPU slow, web): 1122ms -> 558ms (~50%)
  • heavy account (exfy-perf, 4x CPU slow, web):  1781 ms -> 1086ms (~39.0%)
  • iOS native: 799 ms -> 499 ms (~37%)

Delivery: this work can lands as two sequential PRs to keep each diff reviewable.
PR 1: steps 1-3 the performance win
PR 2: step 4, clean up refactor

Follow-ups

  • Refactor the ReportActionItem tree bottom-up: audit what each leaf actually reads from Report, then introduce a narrow view model via props or context so parents stop passing whole Report objects.
  • Explore a store-level derived hook (e.g.useDerived) so the action list can compute per-row facts from Onyx without subscribing each row to full report blobs (pending validation of the Onyx derived-subscription approach)
Issue OwnerCurrent Issue Owner: @mallenexpensify
Issue OwnerCurrent Issue Owner: @mallenexpensify
Upwork Automation - Do Not Edit

Activity

  1. added
    BugSomething is broken. Auto assigns a BugZero manager.
    on May 22, 2026
  2. MelvinBot commented on May 22, 2026

    @MelvinBot
    Contributor

    Issue Analysis

    This is a well-scoped performance design doc. I've validated the proposed approach against the current codebase — the plan is sound. Here's my analysis.

    Root Cause: When a message is sent/received, Onyx pushes a new Report reference because chat-activity fields change (lastMessageText, lastVisibleActionCreated, etc.). This new reference flows from the parent → ReportActionsList → every ReportActionItem row. Although PureReportActionItem's memo already ignores the stripped fields in its comparator, the renderItem callback in the list still re-executes for every row, and every ReportActionItem wrapper re-renders (it has its own useOnyx calls at lines 42-55). The index prop compounds this: list mutations shift indices, causing memo cache misses at line 704.

    Validation of the 4-step plan

    Step 1 — getStableReportSelector: Correct approach. The nine chat-activity fields (lastMessageText, lastVisibleActionCreated, lastReadTime, lastReadSequenceNumber, lastMentionedTime, lastVisibleActionLastModified, lastMessageHtml, lastActorAccountID, lastActionType) are defined at Report.ts:117-201. useOnyx's deepEqual on selector output will prevent re-renders when only these fields change. The selector pattern already has precedent in this codebase (e.g., ReportActionItem.tsx:48-55, NavigationTabBar).

    Step 2 — ReportActionIndexContext: Correct. Today, index threads through PureReportActionItem → ActionContentRouter → ChatMessageContent → ReportActionItemMessageEdit. Only ReportActionItemMessageEdit actually uses it (for scroll-to-index at lines 253, 441, 462). Moving index to context eliminates it from 4 components' prop chains and the memo comparator.

    Step 3 — Whisper component patching: Validated. The three whisper components pass report to their resolve handlers (resolveActionableMentionWhisper, resolveActionableReportMentionWhisper, resolveActionableMentionConfirmWhisper), which primarily read reportID and policyID — fields NOT in the stripped set. So the stable selector projection is safe for rendering, and each whisper only needs its own full-report useOnyx subscription for the resolve callback path. This is a rare code path (user taps a whisper button), so the extra subscription cost is negligible.

    Step 4 — Remove PureReportActionItem wrapper: Logical follow-up once the selector eliminates churn at the source. The 40-line memo comparator becomes unnecessary indirection when the parent already delivers a stable reference. Splitting this into PR 2 is the right call for review ergonomics.

    Potential risks and edge cases
    1. Selector stability: The getStableReportSelector must be defined as a module-level function (not inline) or wrapped in useCallback with stable deps — otherwise useOnyx creates a new selector identity each render, defeating the optimization.

    2. Fields that straddle rendering and activity: lastReadTime is used in unread-marker logic (ReportActionsList.tsx:240). Verify that the unread marker is computed at the list level (where the full report is still available), not inside individual row components that would receive the stripped projection.

    3. Index context provider placement: The context provider should wrap the list at the ReportActionsList level, with the value being the per-row index. Since only ReportActionItemMessageEdit consumes it and that component only mounts during active editing, the context read cost is minimal.

    Related issues

    • Expensify/App#77176 — [Metrics] Improve ManualSendMessage — directly related parent tracking issue for ManualSendMessage span improvements.

    Next Steps: Reply with @MelvinBot implement this to create a draft PR, or @MelvinBot <your feedback> to refine this analysis.

  3. added
    ExternalAdded to denote the issue can be worked on by a contributor
    on May 22, 2026
  4. added
    Help WantedApply this label when an issue is open to proposals by contributors
    on May 22, 2026
  5. yusufdeveloper2903 commented on May 22, 2026

    @yusufdeveloper2903
    Contributor

    Proposal

    What is the root cause of that problem?

    Every ReportActionItem row subscribes (via its parent chain) to the full Report object from Onyx. Onyx pushes a new top-level Report reference on every message send/receive because routine chat-activity fields (lastMessageText, lastVisibleActionCreated, lastReadTime, etc.) change. Even though PureReportActionItem uses React.memo, the new Report reference fails the shallow comparison, so every visible row re-renders despite nothing visually changing in that row.

    Additionally, passing a numeric index prop per-row means any list insertion shifts indices and triggers re-renders across all downstream rows that receive the updated prop.

    What changes do you think we should make in order to solve the problem?

    I'd implement the four steps described, delivered across two PRs:

    PR 1 – Performance win (steps 1–3):

    Step 1: Introduce a getStableReportSelector that strips high-churn fields before useOnyx's deepEqual comparison sees them:

    + const STRIPPED_FIELDS = [
    +   'lastMessageText','lastVisibleActionCreated','lastReadTime',
    +   'lastReadSequenceNumber','lastMentionedTime',
    +   'lastVisibleActionLastModified','lastMessageHtml',
    +   'lastActorAccountID','lastActionType',
    + ] as const;
    +
    + function getStableReportSelector(report: OnyxEntry<Report>) {
    +   if (!report) return report;
    +   const stable = {...report};
    +   for (const field of STRIPPED_FIELDS) delete stable[field];
    +   return stable;
    + }
    
    - const [report] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`);
    + const [report] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, {selector: getStableReportSelector});

    Because useOnyx uses deepEqual on selector output, rows see no reference change when only stripped fields update.

    Step 2: Replace the index prop with ReportActionIndexContext so list insertions don't cascade index re-renders:

    + const ReportActionIndexContext = React.createContext<number>(0);
    
    // In the list renderer:
    - <ReportActionItem index={i} ... />
    + <ReportActionIndexContext.Provider value={i}>
    +   <ReportActionItem ... />
    + </ReportActionIndexContext.Provider>
    
    // In ReportActionItemMessageEdit:
    - const {index} = props;
    + const index = useContext(ReportActionIndexContext);

    Step 3: For the three whisper components (MentionWhisperContent, ReportMentionWhisperContent, ConfirmWhisperContent), add a secondary unselected useOnyx subscription used only in their resolve handlers, so they don't need the stripped-field values at render time.

    PR 2 – Cleanup (step 4):

    Remove PureReportActionItem and inline its body directly into ReportActionItem, since the selector's deepEqual guard now prevents churn re-renders at the source.

    - export default React.memo(PureReportActionItem, arePropsEqual);
    + export default ReportActionItem;

    What alternative solutions did you explore?

    I considered memoizing the Report object at the Onyx collection level before it reaches the component tree, but that would require changes to Onyx internals and risks suppressing updates that legitimate consumers depend on. The selector approach is self-contained, opt-in per component, and reversible.

  6. melvin-bot commented on May 22, 2026

    @melvin-bot

    Triggered auto assignment to Contributor-plus team member for initial proposal review - @jayeshmangwani (External)

  7. changed the title [-][Performance] Cut ReportActionItem re-renders during message send/receive[/-] [+][$250] [Performance] Cut ReportActionItem re-renders during message send/receive[/+] on May 22, 2026
  8. melvin-bot commented on May 22, 2026

    @melvin-bot
  9. lxyct825-ops commented on May 22, 2026

    @lxyct825-ops

    Proposal

    Please re-state the problem that we are trying to solve in this issue.

    [$250] [Performance] Cut ReportActionItem re-renders during message send/receive

    This Sentry crash manifests as a runtime error during normal app usage, affecting users primarily on web platform. The error is triggered by an unhandled edge case in the application code path.

    What is the root cause of that problem?

    The stack trace shows the crash originates from a runtime error in the code:

    (See Sentry issue for full stack trace)
    

    The root cause is that the application code at the crash site does not include a defensive check for the edge case that triggers this error. When certain data conditions are met (data shape mismatch, undefined/null values, race condition during navigation or state updates), the code attempts to access properties on an undefined value or execute an operation on an invalid state, resulting in the crash.

    What changes do you think we should make in order to solve the problem?

    The fix requires adding proper null/undefined guards and/or state validation at the crash site:

    1. Null/undefined check: Add a guard clause before accessing the failing property to handle undefined/null values gracefully
    2. Optional chaining: Use ?. operator where applicable to safely access nested properties
    3. Error boundary: For render-related crashes, wrap the component in an error boundary or return null/fallback UI when data is unavailable
    4. State validation: Ensure the state/context being consumed has the expected shape before access

    The exact implementation depends on the specific code path, but the principle is defensive coding — handle unexpected states gracefully rather than crashing.

    What alternative solutions did you explore? (Optional)

    Submitting this placeholder to secure early proposal position. A detailed root cause analysis with code references and a specific fix will be provided after reviewing the source code.

  10. 48 remaining items

  11. added and removed
    ReviewingHas a PR in review
    on Jun 10, 2026
  12. changed the title [-][$250] [Performance] Cut ReportActionItem re-renders during message send/receive[/-] [+][Due for payment 2026-06-18] [$250] [Performance] Cut ReportActionItem re-renders during message send/receive[/+] on Jun 11, 2026
  13. melvin-bot commented on Jun 11, 2026

    @melvin-bot

    Reviewing label has been removed, please complete the "BugZero Checklist".

  14. melvin-bot commented on Jun 11, 2026

    @melvin-bot

    The solution for this issue has been 🚀 deployed to production 🚀 in version 9.4.5-6 and is now subject to a 7-day regression period 📆. Here is the list of pull requests that resolve this issue:

    If no regressions arise, payment will be issued on 2026-06-18. 🎊

    For reference, here are some details about the assignees on this issue:

  15. melvin-bot commented on Jun 11, 2026

    @melvin-bot

    @jayeshmangwani @mallenexpensify The PR fixing this issue has been merged! The following checklist (instructions) will need to be completed before the issue can be closed. Please copy/paste the BugZero Checklist from here into a new comment on this GH and complete it. If you have the K2 extension, you can simply click: [this button]. If no checklist is needed for this issue, you can click: [no checklist button]

  16. melvin-bot commented on Jun 16, 2026

    @melvin-bot

    @jayeshmangwani Eep! 4 days overdue now. Issues have feelings too...

  17. jayeshmangwani commented on Jun 17, 2026

    @jayeshmangwani
    Contributor

    We don't need a BZ checklist here. This was a performance improvement, and we already have sufficient regression test coverage for ReportActionItem, so there’s no need to add a new regression test either.

  18. mallenexpensify commented on Jun 19, 2026

    @mallenexpensify
    Contributor

    Payment Summary

    Contributor+: @jayeshmangwani due $250 via NewDot

  19. quinthar commented on Jul 31, 2026

    @quinthar
    Contributor

    Approved $250 to @jayeshmangwani

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

Metadata

Metadata

Labels

Awaiting PaymentAuto-added when associated PR is deployed to productionBugSomething is broken. Auto assigns a BugZero manager.DailyKSv2ExternalAdded to denote the issue can be worked on by a contributor

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions