Skip to content

fix: add getSnapshot memoizedShallowEqual to skip rerenders - #819

Open
LukasMod wants to merge 1 commit into
Expensify:mainfrom
callstack-internal:fix/onyx-selector-new-subscriber
Open

fix: add getSnapshot memoizedShallowEqual to skip rerenders#819
LukasMod wants to merge 1 commit into
Expensify:mainfrom
callstack-internal:fix/onyx-selector-new-subscriber

Conversation

@LukasMod

@LukasMod LukasMod commented Aug 5, 2026

Copy link
Copy Markdown

Details

useOnyx no longer changes its result identity when the shared snapshot cache holds a content-equal result from another subscriber

The snapshot cache slot is shared by every subscriber of the same (key, selector) pair, while each subscriber's memoized selector owns a distinct output object. A subscriber that mounts later (its per-hook memoization cache is empty) computes a fresh object, content-equal but referentially new, and publishes it into the slot. Existing subscribers then adopted it blindly in the getSnapshot() fast path, which changed their result identity and re-rendered their memoized subtrees for no reason. The fast path now keeps the hook's own result when the cached one is content-equal (memoizedShallowEqual on the value plus a status match).

Why

We hit this in E/App. In a Concierge chat, every sent message and every Concierge reply re-rendered the whole ReportActionsList content. React DevTools Profiler blamed the report prop of ReportActionsListItemRenderer, and prop-diff instrumentation showed the tell-tale signature on each message: report prop (stableReport <id>): NEW REFERENCE, but every field is shallow-equal. A pure object-identity change with zero data change.

Root cause: every report row (ActionContentRouter) and the report list itself subscribe to the same report_<id> key with the same shared getStableReportSelector. Every incoming message mounts a new row, which republished a fresh identity into the shared slot. That flipped the report prop of every ReportActionsListItemRenderer and re-rendered the entire chat list on each message, even though the selected data never changed. The stable-report projection exists precisely to prevent this class of re-render, and the shared slot was silently defeating it.

Where the fresh object comes from

A projection selector builds a fresh object literal on every call (return {reportID: report.reportID, ...}), so two calls with the same input produce two content-equal objects with different identities. Identity stability is never provided by the selector itself. It comes from the per-hook memoized wrapper (createMemoizedSelector), which deep-compares each recompute against its lastOutput and returns the old reference when equal. A newly mounted subscriber has no lastOutput yet, so the fresh literal becomes its output and gets published into the shared slot, where the other subscribers' fast paths adopted it.

Why a per-call-site selector wrapper also "fixes" it (and why it's not the fix)

The slot key is ${key}_${selectorID}, where selectorID is assigned per function identity. Wrapping the shared selector in a module-level function (const stableReportSelectorForList = (report) => getStableReportSelector(report)) mints a new identity, giving that call site a private slot with a single writer and reader, which is the always-working sole-subscriber case. But that only shields one call site. All remaining subscribers of the shared selector keep flipping each other in their shared slot. The fast-path guard fixes the adoption itself, making sharing safe for every consumer without per-call-site workarounds. (The wrapper must be module-level. Defined inside a component it would mint a new identity every render, causing cache-slot churn and a selector recompute per render.)

Why this implementation

  • Guard only the fast path. The recompute path already preserves identity via the memoizedShallowEqual check on previousValueRef. The fast path was the single place adopting a result without any comparison.
  • Near-zero cost. Converged and single-subscriber hits short-circuit on the first !== pointer compare. Distinct-but-equal objects pay one top-level walk, memoized by identity pair in the memoizedShallowEqual WeakMap, so N hooks comparing the same two objects pay for one walk total. Real content changes arrive via slot invalidation (recompute path), so the guard rarely sees them.
  • Status must match too. A cached loaded result never masks this hook's loading state (and vice versa). Value equality alone isn't enough to skip adoption.
  • Regression test reproduces the exact failure: an existing subscriber's result identity must survive a new subscriber mounting with the same key and selector. It fails on the previous code at the identity assertion and passes with the guard. The full useOnyx suite is unaffected.

Before:

concierge baseline

After:

concierge fixed
Scenario Before After Change
ManualSendMessage - Concierge chat (narrow web) 301 ms 237 ms -21.1%
ManualSendMessage - DM test 465 ms 336 ms -27.7%

Related Issues

Expensify/App#95584

Linked E/App PR

Expensify/App#97952

Automated Tests

Manual Tests

No visible changes. Smoke tests:

Test 1: Send messages in open report

  1. As account A, open Report A
  2. Send 5 messages in quick succession
  3. Confirm each message appears
  4. Confirm the LHN row for Report A shows the last sent message as its preview

Test 2: Rapid report switching

  1. As account A, switch between Report A and Report B 5 times quickly
  2. Confirm each report shows its own content immediately
  3. Confirm no report gets stuck in a loading skeleton
  4. Send a message mid-switching and confirm it lands in the right report

Author Checklist

  • I linked the correct issue in the ### Related Issues section above
  • I linked the corresponding Expensify/App PR in the ### Linked E/App PR section above, and verified this change against it (E/App CI passed and manual testing completed)
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • 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 / Chrome
    • iOS / native
    • iOS / 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 the left part of a conditional rendering a React component is a boolean and NOT a string, e.g. myBool && <MyComponent />.
    • 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 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.js 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 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
    • If we are not using the full Onyx data that we loaded, I've added the proper selector in order to ensure the component only re-renders when the data it is using changes
    • 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 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 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 author checklist, including those that don't apply to this PR.

Screenshots/Videos

Android: Native

Android: mWeb

ChromeiOS: Native

iOS: mWeb Safari

MacOS: Chrome / Safari

Screen.Recording.2026-08-06.at.15.28.59.mov

@LukasMod

LukasMod commented Aug 5, 2026

Copy link
Copy Markdown
Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: 96a7ddec43

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

@LukasMod
LukasMod marked this pull request as ready for review August 7, 2026 06:13
@LukasMod
LukasMod requested a review from a team as a code owner August 7, 2026 06:13
@melvin-bot
melvin-bot Bot requested review from arosiclair and removed request for a team August 7, 2026 06:13

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

Should we run wider tests for this change?

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.

3 participants