Skip to content

[Metrics] Explore navigation-layer solution for ManualSendMessage spans (react-navigation 8 inactiveBehavior) #97081

Closed

Description

@cristipaval

Context

Spun off from #95584 (comment)

The current proposal reduces ManualSendMessage span time via onyx-around focus logic, but it carries trade-offs and extra code complexity. Before moving forward, explore an alternative that resolves the same issue at the navigation layer, so focus logic lives where it belongs — in navigation, not around Onyx.

What to explore

  • react-navigation 8 inactiveBehavior option for all navigators
  • Activity mode "hidden" for keeping screens visible/mounted

References:

Note

react-navigation 8 is in alpha. Assess viability, migration cost, and whether this removes the need for the onyx-around approach.

Parent

Part of #77176

Issue OwnerCurrent Issue Owner: @LukasMod

Activity

  1. LukasMod commented on Jul 29, 2026

    @LukasMod
    Contributor

    Still investigating. I hope I'll be able to share some details tomorrow. I'm testing on web only right now. The mechanism behaves a bit differently than the idea of freezing useOnyx.

    At the moment, I'm dealing with some issues related to list scrolling. I'm trying to get a minimal working version and then list the pros and cons based on the experiments. As expected, this bump won't be straightforward.
    Im trying to pause the same screen as in #95584 (comment). Rerenders are properly deferred and there is ~30% boost, similar.

    Image
  2. LukasMod commented on Jul 30, 2026

    @LukasMod
    Contributor

    Update:

    POC DRAFT: #97477

    Result:
    Spend Tab -> Reports -> Report with multiple transactions (rhp) -> Open Report (rhp) -> Send message

    Platform Baseline Mean RN8 Mean Improvement
    Web (exfy-perf heavy account) 626 ms 159 ms -74.6%
    iOS 1289 ms 735 ms -42.9%
    Android 940 ms 453 ms -51.7%

    Pros:

    • Optimization lives entirely in the navigation layer - no Onyx or component changes.
    • Paused screens stay painted and eventually consistent (deferred updates still land, no stale flash on return in most cases).
    • State, refs, DOM, scroll all survive pause.
    • Per-screen opt-in (patched pauseWhenCovered on 5 heavy list screens in PoC) - blast radius controlled and declarative.

    Cons:

    • Effect lifetimes change: cleanup runs on pause, effects re-run on resume - every mount-effect/cleanup-as-close idiom in a pausable screen is a potential bug (found few regarding scrolling and animating).
    • Reanimated web exit/layout animations flicker under pause (currently disabled on Expense listing).
    • Work is deferred, not eliminated; content under blur can lag during sustained activity; 500ms pause delay (from rn8).
    • Deferred renders don't show up in React DevTools Profiler as expected - paused screens look like they never render, which makes verification and debugging misleading (it's still visible in Performance tab)
    • Known open issue: deeplinking directly to an RHP screen leaves the content below the RHP missing (underlying screen doesn't render when the RHP is the entry point). Example video below.
    • Two patches on alpha packages to re-port every bump (one with pauseWhenCovered, one to cover multiplatform settings and required anyway when migrate to v8)

    All flickering/scroll issues found so far were solved on the E/App side (ref guards for resume-effect re-runs, gating animations). I could not reproduce any of them in the react-navigation example app (ScrollView/FlatList/FlashList all survive pause round-trips there), which points to E/App code patterns, not framework bugs.

    Perspective:
    most of the branch diff is generic v8-alpha migration (options conversion, getParent semantics, API renames, dropped v7 patches). The pause mechanism itself is small, one screen option in CardStack plus five per-screen flags.

    Profiler example (Baseline rn7 main):

    Image

    Profiler example (rn8 with pauseWhenCovered):

    Image

    Example how deferred update works with CPU slowdown x6:

    update.from.rhp.cpu.slow.x6.mov

    Example how deferred update works with CPU no slowdown:

    update.from.rhp.mov

    Example how deeplink to RHP with paused content below looks like (no content from previous renders):

    deeplink.with.rhp.mov
  3. LukasMod commented on Jul 31, 2026

    @LukasMod
    Contributor

    I updated #97081 (comment) with native platform results.
    I was able to update to react-gesture-handler 3 and use Legacy imports instead of full migration for PoC.

    I didn't spot issues in my benchmark scenario. Scroll holds, updates are deferred.
    I created a React Navigation PR to get the maintainers opinion on this change: react-navigation/react-navigation#13200.

    Also maybe its worth to check AdHoc on this one and play around a bit? #97477 @cristipaval Could you run it? I checked with dev builds so far

    iOS baseline:

    Image

    iOS rn8 with pauseWhenCovered:

    Image

    Example how backTo looks like on iOS:

    rn8-ios-back.mov
    Latest Session Summary

    React Navigation 8 alpha PoC — Summary

    Branch: poc/rn-8-alpha (web + native PoC, typecheck deliberately skipped)
    Goal: Verify whether RN8's inactiveBehavior / React <Activity> stops blurred-screen re-renders that inflate ManualSendMessage (#95584, callstack-internal/expensify-issues#2683).

    Headline result

    Scenario: heavy account, Spend tab Reports listing → open SearchMoneyRequestReport (wide RHP) → open a report from it → send a message → measure the send-message span.

    Platform Baseline mean RN8 mean Improvement
    Web (exfy-perf heavy account) 626 ms 159 ms −74.6%
    iOS 1289 ms 735 ms −42.9%
    Android 940 ms 453 ms −51.7%

    The screens under the covers are genuinely paused: useOnyx subscriptions unmount, so an Onyx write during send cannot synchronously re-render a covered screen — that work still happens, but as a deferred render at idle priority, off the interaction's critical path.

    Measured under the final model on all three platforms: per-screen flags on the five heavy list screens + the external-cover extension in both stacks, TabNavigator itself not paused. The win comes from the expensive under-cover screens (Search listing, SearchMoneyRequestReport, the report screen) each pausing individually. Web measured 2026-07-30; iOS/Android measured 2026-07-31 after the native-stack port.

    How React <Activity> (pause) actually works

    RN8's inactiveBehavior: 'pause' wraps the screen in React's <Activity mode="hidden">. What that does:

    1. Hides via display: none (inline, !important) and runs every effect's cleanup function — from React's perspective a pause is indistinguishable from an unmount for effects. State, refs, and the DOM tree are all preserved.
    2. Deferred, not frozen. A hidden tree still processes updates — React just downgrades them to Offscreen (idle) priority. Context changes and parent re-renders penetrate the Activity boundary and eventually render + commit to the (hidden) DOM in background commits. So hidden content does update, with low priority, off the critical path — that's the entire perf win: the work still happens, but no longer inside ManualSendMessage.
    3. Subscriptions can't push, but renders pull fresh data. useOnyx's useSyncExternalStore subscription is torn down on pause (effect cleanup), so Onyx can't trigger the hidden screen. But whenever a deferred render pass reaches it (e.g. an Onyx-connected context provider above the navigator updated), getSnapshot re-reads the current Onyx value during render — which is why a merchant edited in the RHP appears in the paused list under the blur. React DevTools Profiler barely surfaces these hidden-tree offscreen commits, so it looks like "no render happened".
    4. Effect cleanup on pause is the real migration cost. Four failure classes hit in this codebase alone:
      • Cleanup used as an "I closed" signal fires on pause too — useRHPWidth.onClose collapsed the wide RHP when a second RHP covered it. Fix: cleanup checks the route key is still in navigationRef.getRootState().
      • []-deps "on mount" effects re-run on every unpause — the initial scroll-to-bottom in useReportActionsScroll re-fired when a paused chat resumed and destroyed the restored scroll position. Fix: guard with a ref (refs survive pause; only effects remount).
      • "Skip first run" ref+effect idioms invert their meaning — useAccordionAnimation uses a hasMounted shared value to suppress the mount animation; on unpause the effect re-runs with the ref already set, so the mount animation plays on every resume (observed as Search sidebar accordions animating on each tab switch when tab-level pausing was trialed). No code fix in place — CAUTION: inactive tab scenes still pause via stock bottom-tabs, and the Search sidebar lives in a tab scene, so the idiom is still reachable on tab switches — retest (switch away from Search and back, watch sidebar accordions). Fix if it reproduces: guard on the actual value change (compare previous isExpanded), not on mount count.
      • General audit rule: grep pausable screens for hasMounted / didMount / isFirstRender / cleanup-as-close patterns before shipping.
      • Reanimated web layout/exit animations flicker at the pause kick-in (confirmed 2026-07-30 by bisect on the Expense Search listing): rows wrapped in Animated.View with exiting/layout props (AnimatedExitRow) visibly flicker ~500ms after an RHP covers a pauseWhenCovered screen. Reanimated web measures via getSnapshotBeforeUpdate/componentDidUpdate DOM rects; the pause display: none → keep-visible rewrite cycle gives it garbage (0-rect) measurements to animate from. The Reports listing (no animated rows) is unaffected — the animated wrapper was the exact differentiator. Current state: shouldApplyAnimation hard-disabled in ExpenseFlatSearchView as a stopgap; proper fix is gating the animation props while the screen is covered/paused (e.g. useIsFocused) or fixing the Reanimated-under-Activity interplay.
    5. DOM-owned side effects persist while hidden. Unmount destroys elements, so the browser stops their behavior for free; hide keeps them alive: <video>/<audio> keep playing, iframes keep running scripts/network, imperative DOM listeners added outside effects keep firing. The keep-visible mechanism (stock ActivityView) amplifies this — paused content stays painted. Anything noisy must be stopped explicitly in effect cleanup (e.g. video.pause()).
    6. 500ms delay: ActivityView pauses a screen only after it has been covered for 500ms (mode is delayed; display is not), so interactions within that window still hit an unpaused screen.
    7. Native keep-visible works differently, but is also stock. ActivityView.native.js doesn't use a MutationObserver — it renders a custom native view (ReactNavigationActivityContentView) whose display style prop is force-processed to 'contents' in its view config, so React's display: none on pause is neutralized at the native level; actual visibility is controlled by an inner Container, and inert is applied for any non-'normal' mode. Same 500ms delay. Consequence: everything the web patch gets from keep-visible (paused-but-painted) comes for free on native too — no elements patch on either platform.

    Key analysis finding (why a patch is needed at all)

    Stock v8 never pauses the screen under the RHP. The CardStack heuristic keeps a screen 'inert' (mounted, effects running, re-renders committing) when it is before-last or under a transparentModal — which is exactly Expensify's RHP (presentation: TRANSPARENT_MODAL). 'paused' (real <Activity mode="hidden">) is only reached for screens buried 2+ deep in one stack. TabNavigator is always before-last in the root stack ([TabNavigator, RightModalNavigator]), so no v8 option combination pauses it.

    The same holds on native: NativeStackView's stock chain keeps focused, preloaded/retained, previous (swipe-back) and transparent-covered screens unpaused, so the screen under a transparent RHP or before-last stays live there too — and both stacks are equally blind to external covers (an ancestor navigator's cover), since each stack only compares route indexes inside itself.

    The patches (patches/react-navigation/)

    Inventory — what exists, whether it's required, and the evidence

    Patch hygiene (2026-07-31): the stack and native-stack patches were regenerated from pristine node_modules after the option change. The old stack patch was a single hunk — @@ -1,543 +1,618 @@, the whole file — because a formatter (oxfmt: no space inside braces, single quotes, 4-space indent) had been run over the hand-edited CardStack.js in node_modules, so every line differed from the published package. Of its 1123 lines, 19 mentioned the feature. Now: 82 lines / 6 hunks (stack) and 68 lines / 6 hunks (native-stack), containing only real changes. This matters on alpha packages — the old patch broke if upstream touched any line of CardStack.js; the new one only if upstream touches one of five anchored regions. When editing files under node_modules, keep the formatter out of the loop (edit via script, or revert-and-reapply) before running npx patch-package <pkg> --patch-dir patches/react-navigation.

    Exactly three patches, all authored in this PoC (none upstream, none inherited verbatim from v7 — only dontDetachScreen and the core options conversion port v7 behavior). Every "required" verdict was established empirically: break observed live, patch applied, break gone. Everything else in react-navigation — including elements' ActivityView keep-visible (web MutationObserver / native display: contents view config) and bottom-tabs scene handling — runs stock, verified sufficient by testing.

    Patch Required What breaks without it (observed, not theoretical)
    @react-navigation+stack (web) YES (a) dontDetachScreen: split sidebars vanish — Inbox LHN and Settings sidebar simply missing on wide layout after the v8 bump. (b) pauseWhenCovered: no pausing exists in stock v8 for our positions — send-message regresses from 159 ms back to ~626 ms. (c) external-cover extension: without it, per-screen flags on tab-nested screens never fire under an RHP (verified: the SCREENS.REPORT flag "did nothing" until this was added).
    @react-navigation+native-stack (native) YES Same gap as (b)+(c) on iOS/Android: NativeStackView has no way to pause a screen under a transparent RHP, before-last, or under an ancestor stack's cover. Without it the native: {inactiveBehavior: 'pauseWhenCovered'} flags do nothing and native keeps every covered screen live.
    @react-navigation+core YES Every platform-nested option silently dropped: RHP loses transparentModal (screens under it hidden entirely), Spend tab content invisible, no dim overlay, wrong/missing transitions — all observed after the bump, all traced to this single root cause. Also the delivery path for the new native: {...} flags, so it is required on both platforms.

    The option: inactiveBehavior: 'pauseWhenCovered'

    Shape change (2026-07-31): the opt-in started as a standalone boolean screen option (pauseWhenCovered: true) and is now a fourth value of the existing inactiveBehavior option: 'pause' | 'pauseWhenCovered' | 'unmount' | 'none'. Reasons: v8's inactiveBehavior is itself the consolidation of the old freezeOnBlur / detachPreviousScreen booleans, so a new boolean in the same problem space invites "why isn't this an inactiveBehavior value?"; and the enum makes the contradictory combination {inactiveBehavior: 'none', pauseWhenCovered: true} — which the boolean version silently resolved in favour of pausing — unrepresentable. Cost: it can no longer be combined with 'unmount' ("unmount when buried, pause when merely covered"), which nothing needs today. The patches also extend the inactiveBehavior union in each package's lib/typescript/src/types.d.ts, so app code typechecks against the value.

    @react-navigation/stack — CardStack heuristics: how pauseWhenCovered works

    The patch lives in CardStack.js's per-scene render loop. All decisions stay inside CardStack — screens/ActivityView/React are unmodified downstream consumers of the mode/visible pair it computes.

    Knob 1 — inactiveBehavior: 'pauseWhenCovered' (screen option). Semantics for a flagged screen: "pause me whenever anything covers me — a screen pushed in my own stack or an ancestor stack's cover — and keep me painted." Uncovered/focused → fully stock behavior.

    Knob 2 — dontDetachScreen (route flag derived from persistentScreens): forces mode='normal' + visible=true — replaces the dropped v7 dontDetachScreen patch. Without it split sidebars (route[0], covered by the central screen) get isVisible: false and the Inbox LHN / Settings sidebar vanish on wide layout. 'normal' (not 'paused') because sidebars are blurred-but-clickable by design. Expensify-only — this knob is not part of the upstream proposal.

    The four code changes:

    1. External-cover source: static contextType = IsFocusedContext on the CardStack class, read in render as isCoveredExternally = this.context === false. IsFocusedContext is ancestor-composed — core's NavigationProvider provides parentIsFocused ? focusedRouteKey === route.key : false per screen — so it is false exactly when any ancestor navigator has focus elsewhere (e.g. the root stack focused on the RHP, not the TabNavigator). undefined (root navigator, no provider above) is treated as focused. (Earlier revisions wrapped the class in a function component that read the context via React.use and passed an isParentFocused prop; contextType does the same with no wrapper and no prop plumbing.)

    2. One isCovered flag, computed next to the other position flags:

      const isCovered = !isFocusing && (focused
        ? isCoveredExternally
        : !isInactive && !isRetained && (isNextScreenTransparent || isBeforeLast));

      The focused and !focused cases are mutually exclusive, so the two pause branches an earlier revision needed collapse into this one boolean. !isFocusing keeps a screen live mid-transition; !isInactive && !isRetained leaves preloaded and retained screens to the stock rules.

    3. isVisible clause: dontDetachScreen || (pauseWhenCovered && isCovered) || … prepended to the stock visibility disjunction. Without the pause clause, an in-stack-covered opaque card would get mode='paused' with visible=false — plain display: none, defeating keep-visible.

    4. activityMode ternary — one new leading branch plus the Expensify knob, in evaluation order:

      1. pauseWhenCovered && isCovered → 'paused' — covers both the external case (RHP over the tab) and the in-stack case (under a transparentModal, or before-last). Those two in-stack positions are exactly the ones stock v8 hard-codes to 'inert' (mounted, subscriptions live, re-renders committing synchronously) with no option to change it.
      2. focused || isFocusing → 'normal' (stock).
      3. dontDetachScreen → 'normal' (knob 2, Expensify-only).
      4. Stock chain unchanged: 'inert' / 'unmounted' / 'paused' (the stock 'paused' is only reachable 2+ deep under opaque cards).

    What mode='paused' changes downstream: ActivityView (elements) flips its inner <Activity> to mode="hidden" after the stock 500ms delay (display handling is not delayed). React then runs every effect's cleanup (subscriptions — useOnyx — unmount), preserves state/refs/DOM, and downgrades all future renders in that subtree to Offscreen/idle priority. ActivityView's stock keep-visible MutationObserver rewrites React's inline display: none !important so the paused card stays painted (scroll survives the flip on its own — browsers restore it, and the app-level ref guards stop resume-effect yanks). Net effect per flagged screen: an Onyx write during an RHP interaction can no longer re-render it synchronously — its updates run as deferred renders at idle — while it remains visible under the blur with intact scroll/DOM.

    What it costs: the pause blast-radius — effects re-run with unchanged deps on every resume (see failure classes: scrollOffsetStore reset, cleanup-as-close, mount-guard inversion, Reanimated flicker). This is why the flag is per-screen on five audited screens instead of navigator-wide.

    inactiveBehavior is never set explicitly — 'pause' is the v8 default and only enters the heuristic for screens buried 2+ deep under opaque cards.

    @react-navigation/native-stack — NativeStackView: pauseWhenCovered on native

    The native port mirrors the CardStack patch: same option value, same single pause branch, same external-cover mechanism — adapted to NativeStackView.native.js's scene model.

    1. External-cover source: NativeStackView reads React.use(IsFocusedContext) (imported from @react-navigation/native) and passes isCoveredExternally down to every SceneView. undefined (root navigator) is treated as focused, exactly as on web. No wrapper and no contextType needed — NativeStackView is already a function component.
    2. One isCovered flag + one new activityMode branch, ahead of the stock chain:
      const isCovered = focused ? isCoveredExternally : !isInactive && (isNextScreenTransparent || isBeforeLast);
      // pauseWhenCovered && isCovered ? 'paused' : <stock chain>
    3. Sheet / partial-modal covers are NOT excluded (changed 2026-07-31). An earlier revision copied stock's !isNextScreenSheet && !(isNextScreenModal && !isModal) carve-outs, which made native diverge from web: a formSheet or an iPad modal left a flagged screen fully live. Removed, because stock's own stated reason for those carve-outs is freshness ("so it stays up to date") — precisely the tradeoff this option exists to make — and because the option's purpose is pausing screens that remain visible under a cover (that's the transparentModal/RHP case on both platforms). All three implementations now reduce to the same rule: not focused ∧ not preloaded/dismissing ∧ (next screen transparent ∨ before-last) → paused.
      • Residual cost, documented rather than carved out: a paused screen gets pointerEvents: 'none' (elements' Container applies inert for any non-'normal' mode). Behind a dimmed sheet or iPad modal iOS already blocks touches, so this only bites with sheetLargestUndimmedDetentIndex, where the background is deliberately left interactive. Don't flag screens used that way.
    4. No isVisible clause needed (unlike web): ActivityView.native decouples visibility from Activity via the display: contents view-config trick plus an inner Container, so a paused screen stays painted without the extra visibility disjunction the web patch adds. The stock 500ms delay applies identically.
    5. No dontDetachScreen on native — that knob exists only in the web patch (split sidebars are a web wide-layout concern).

    Screen flags are declared per platform on the same five screens: {web: {inactiveBehavior: 'pauseWhenCovered'}, native: {inactiveBehavior: 'pauseWhenCovered'}} in ReportsSplitNavigator / SearchFullscreenNavigator, and the same value merged into the existing web / native spreads for the three RightModalNavigator report screens. Both keys reach the navigator only through the core options-conversion patch.

    pauseWhenCovered settings audit (verified 2026-07-30, flags extended to native 2026-07-31)

    Declarations in the table below are written in the original boolean shorthand (: true). They all now read inactiveBehavior: 'pauseWhenCovered'; the decisions themselves are unchanged.

    Stock behavior for covered screens (the analysis behind each decision): stock v8 hides a covered screen only when the cover is opaque AND animation is disabled — then the covered card gets 'inert' + isVisible: false (hidden-but-live). Under a transparentModal, or with animation enabled (the "keep last two routes visible" clause), stock keeps the covered card painted and live ('inert') — visually fine, but re-rendering synchronously on every Onyx write while covered. Note: hidden-but-live itself is survivable (browsers restore scrollTop across display: none; verified), so the keep/remove criterion is perf on heavy list screens, not scroll protection.

    External covers: the base flag was per-stack blind — a route only saw covers inside its own navigator, so an RHP (root stack) could never pause anything inside the TabNavigator; the per-screen flag on SCREENS.REPORT initially "did nothing". Fixed by the external-cover extension (mechanics in the patch section above); with it a flagged screen pauses under ANY cover. A flagged screen inside an inactive bottom-tab scene is paused by both this and stock tab pausing (consistent, no conflict).

    Declaration Decision Why
    useSplitNavigatorScreenOptions.centralScreen: true REMOVED (navigator-wide) Manual verification: central-over-central WITHOUT the flag still preserves scroll — hidden-but-live is survivable because modern browsers restore scrollTop across display: none. Moved per-screen (below). The sidebar: false opt-out became unnecessary with it.
    ReportsSplitNavigator per-screen: SCREENS.REPORT: true KEPT — perf, targeted The heavy chat list. Covered (by an RHP via external cover, or by another central screen), stock leaves it re-rendering synchronously on every Onyx write; pausing defers that work off the critical path and keeps the card painted. Settings/workspace central screens (light forms) stay stock.
    useRootNavigatorScreenOptions.fullScreen: true REMOVED Hazard class exists structurally (animation: NONE, opaque-over-opaque root screens), but every consumer (ValidateLogin, NotFound, ConnectionComplete, BankConnectionComplete, ShareModalNavigator) is static/transient — nothing to protect. Re-add if a scrollable fullscreen root screen appears.
    useRHPScreenOptions: true REMOVED (navigator-wide) Every RHP screen is a transparentModal — a covered RHP screen stays visible + live (inert) in stock v8. Blanket pausing prevented nothing on light form/step screens and re-fired mount-time effects on resume (the scrollOffsetStore bug, useRHPWidth.onClose).
    useModalStackScreenOptions: true REMOVED (blanket) RIGHT_MODAL screens: transparent (see above). Nested modal-stack steps: opaque but animation-enabled, so the before-last step stays painted via stock's last-two-visible clause; deeper steps are outside the flag's reach anyway.
    RightModalNavigator per-screen: SEARCH_REPORT, EXPENSE_REPORT, SEARCH_MONEY_REQUEST_REPORT: true KEPT — perf, targeted The heavy report/transaction-list RHP screens. Covered by the next RHP screen (send a message in a transaction thread opened from a wide report), 'inert' would re-render them synchronously on every Onyx write — this IS the PoC's measured scenario. Per-screen instead of navigator-wide so light RHP flows keep stock semantics. Resume-effect guards required on these screens (in place: scrollOffsetStore ref guard, useRHPWidth.onClose).
    useRootNavigatorScreenOptions.splitNavigator: true REMOVED — dead No consumer: nothing in AuthScreens.tsx uses .splitNavigator; Workspace/Domain split routes get local options (WorkspaceNavigator.tsx).
    fullScreenTabPage: unset deliberate Pausing the whole TabNavigator under the RHP showed visible flicker/jumps in the blurred tab content at the 500ms pause kick-in. Root cause was NOT the pause display cycle itself — later findings traced flicker to animations re-running under pause (Reanimated exit/layout rows, useAccordionAnimation mount-animation replay on resume), all fixable app-side; tab-level pause was not re-tried after those fixes. Kept unset anyway: the per-screen model already captures the perf win with a far smaller resume-effect blast radius. Consequence: the TabNavigator route itself never pauses, and unflagged screens inside tabs stay fully live under the RHP blur; the flagged ones (SCREENS.REPORT, SEARCH.ROOT) still pause individually via the external-cover extension.
    SearchFullscreenNavigator → SEARCH.ROOT: true (explicit per-screen) KEPT — perf, targeted Search listings (Reports/Expense tables). Meaningless per-stack (only screen in its stack) but fires via the external-cover patch extension when an RHP opens over the tab. Exposed the Reanimated flicker on the Expense table (see failure classes) — animated rows hard-disabled as a stopgap.

    Current state: pauseWhenCovered is per-screen only, on the five heavy list screens, on both web and native — SCREENS.REPORT in ReportsSplitNavigator, SEARCH.ROOT in SearchFullscreenNavigator, and SEARCH_REPORT / EXPENSE_REPORT / SEARCH_MONEY_REQUEST_REPORT in RightModalNavigator. With the external-cover patch extension (present in both stacks), each pauses whenever covered by anything — a same-stack push, the next RHP screen, or a root-level RHP over the tab (the send-message scenario, verified working). Rationale: a covered heavy screen left 'inert' re-renders synchronously on every Onyx write while covered; pausing defers that work off the interaction's critical path and keeps the card painted. Everything else — navigator-level split options, RHP navigator options, modal stacks, root fullscreen — runs stock v8 semantics, keeping the pause blast-radius (resume-effect re-runs, Reanimated flicker) confined to five screens with known guards (scrollOffsetStore ref guard, useRHPWidth onClose route-key check, useReportActionsScroll initial-scroll ref guard — all active). Inactive tab scenes still pause via stock bottom-tabs behavior (separate mechanism, no patch). What this buys, concretely: per-screen under-RHP pausing (the measured −74.6% send-message), RHP-under-RHP pausing on the three heavy report screens, central-over-central deferral on SCREENS.REPORT, and split sidebars existing at all (dontDetachScreen).

    Why the stack patch is needed at all (verified against the tree): our perf problem lives exactly in the two positions stock v8 refuses to pause. The screens that re-render on every Onyx write during an RHP interaction are, by construction, either before-last in their stack or under a transparentModal — and stock CardStack hard-codes both cases to 'inert' (mounted, subscriptions live, re-renders committing synchronously). inactiveBehavior can't reach them: it only applies to screens buried 2+ deep under opaque cards. So no upstream option combination defers that work; pauseWhenCovered is the missing knob — <Activity mode="hidden"> (subscriptions unmounted, renders deferred to idle) plus ActivityView's stock keep-visible (DOM stays painted, no scroll/layout loss). The same patch also carries dontDetachScreen, without which v8 hides split sidebars entirely (isVisible: false for covered opaque cards).

    @react-navigation/core — per-layer options conversion (ported from v7)

    useNavigationBuilder/useDescriptors accept a 3rd convertCustomScreenOptions argument and flatten each custom {web: {...}, native: {...}} options layer (navigator screenOptions, Group options, Screen options, setOptions overrides) before merging — so a screen-level web object merges key-by-key on top of the navigator-level one, exactly like v7. The per-layer placement matters: converting the already-merged result instead makes a screen-level web object clobber the navigator-level one wholesale. v8 ships ESM only (lib/module), so a single build is patched.

    Why needed / scenario: Expensify's entire options system is written as {web: {...}, native: {...}} nested objects, which stock react-navigation does not understand — without conversion every web-nested option is silently ignored. Observed symptoms after the v8 bump, all traced to this one root cause: Spend tab content invisible (cards without cardStyle starved the flex layout), RHP screens losing presentation: transparentModal (the stack no longer treated the RHP as transparent, so screens under it were hidden instead of shown — and could never pause), no dim overlay, wrong/missing transition animations. Lesson: any option-merge behavior difference surfaces as layout/visual bugs far from the cause (a merged-result conversion instead of per-layer broke SearchReport/ExpenseReport by clobbering their inherited presentation).

    Scroll and hidden-layout: no patch needed (verified)

    Everything scroll/visibility-related outside CardStack runs stock and works:

    • Keep-visible is stock upstream: elements' ActivityView (alpha.44) ships the MutationObserver that rewrites React's inline display: none !important back to visible — paused-but-painted comes for free.
    • Browsers restore scroll across display: none natively (CSSWG scroll restoration) — verified in the react-navigation ActivityModes harness with ScrollView, FlatList, and FlashList 2.3.0, and in Expensify itself (scroll → cover with RHP → pause → back: no missing rows, no scroll loss; update-while-hidden tab round-trips: layout and scroll fine).
    • Every real scroll yank was app-level: mount-time effects re-running on Activity resume. Fixed with ref guards that survive pause: scrollOffsetStore.setOffset(0) in MoneyRequestReportUnifiedList, and the initial scroll-to-bottom in useReportActionsScroll (didScheduleInitialScrollRef — without it, Inbox → report → open RHP from preview → close visibly yanks the chat).

    Fallbacks, should either hazard ever materialize: a scroll record/restore for the pause hide-flip (capture-phase scroll recording + one synchronous restore on the hidden→visible rewrite; working code in the elements patch at commit 805aa7d69a0); for a tab returning with collapsed/blank list layout after background updates (the measure-at-0 mechanism inside display: none trees is real), keep loaded scenes painted via visible: true in BottomTabViewCustom (bottom-tabs).

    v8 breaking changes found (each failed silently)

    1. getParent(arg) matches by route name, not navigator id (removed in v8), and self-matches. useResponsiveLayout's getParent(NAVIGATORS.RIGHT_MODAL_NAVIGATOR) matched the RightModalNavigator's own route → the RHP considered itself "in a narrow pane" → no dim overlay + RHP stretched to 100% width. Final fix: dropped navigation introspection entirely — both hook variants read NarrowPaneContext (provided by RightModalNavigator around its screens, already consumed by ScreenWrapper/BaseModal), which self-excludes the navigator naturally and doesn't depend on alpha getParent semantics.
    2. The v7 core patch (platform-navigation-stack-types.patch) was not types-only. Dropping it silently discarded every web-nested option (presentation, cardStyle, cardStyleInterpolator, transitionSpec, cardOverlayEnabled) — root cause of the RHP losing its transparent presentation, broken card layouts (starved SearchSidebar/StackView flex), and missing overlays. Fixed by porting the runtime part to v8 core (see above). Corollary: any option-merge behavior difference surfaces as layout/visual bugs far from the cause.
    3. Activity pause redefines effect lifetimes — see "How Activity works" §4. Applies to every pausable screen (focus traps, shortcut registries, close-time analytics, initial scrolls/fetches, skip-first-render animation guards).
    4. React hides <Activity> content with inline display: none !important. Sounds like it should lose scroll and cache zero-based layout in hidden trees — verified NOT to in practice: no navigation-layer fix needed (see "Scroll and hidden-layout" above). Browsers restore scroll across display: none natively; every real scroll yank was an app-level resume-effect re-run fixed with ref guards.

    Other v8 API fixes (boot)

    • useNavigationBuilder no longer returns describe — removed from createPlatformStackNavigatorComponent (both variants).
    • CommonActions.navigate positional args (linkTo/index.ts).
    • preloadedRoutes folded into routes — Navigation.clearPreloadedRoutes() slices routes instead.
    • bottom-tabs needs implementation="custom" for a custom tabBar; freezeOnBlur removed (TabNavigator.tsx / .native.tsx).
    • v8 useIsFocused throws without IsFocusedContext — withNavigationFallback now provides a live fallback (focus/blur subscription) for components mounted outside screens.
    • freezeOnBlur is gone from bottom-tabs, so react-native-screens no longer freezes inactive tabs — inactive tab scenes now pause via stock v8 Activity handling instead. The app's own react-freeze machinery is still in the tree and still active (FreezeWrapper on web tab content, wrapDescriptorsWithFreeze via freezeNonTopScreens: true in createSplitNavigator); <Activity> has not replaced it yet. Removing it is a follow-up — it now overlaps with pause on the same screens.
    • All 15 v7 react-navigation patches + 4 react-native-tab-view patches deleted; re-evaluation notes in patches/react-navigation/details.md.

    Native enablement (2026-07-31)

    • react-native-gesture-handler 2.32.0 → 3.1.0 — a hard peer requirement of @react-navigation/stack@8 (react-native-gesture-handler: >= 3.0.0), so the bump was not optional. RNGH 3 renamed its wrapped RN component re-exports, which cost:
      • 11 app call sites moved to the Legacy* names (LegacyFlatList, LegacyTextInput, LegacyScrollView, …) — AttachmentCarouselView, BaseAutoCompleteSuggestions, ImageCropView, DraggableList/index.native, MultiGestureCanvas pan/pinch/tap hooks, TimePicker, onboarding purpose/track-goal screens, DynamicTravelTerms.
      • a 4th react-native-draggable-flatlist patch (004+gh3-legacy-imports) — the library imports FlatList/ScrollView from RNGH directly, in both lib/module and src.
    • @react-navigation/native-stack patch (see the patch section) plus native: {inactiveBehavior: 'pauseWhenCovered'} on the five flagged screens.
    • iOS and Android builds run with this model; numbers in the headline table (iOS −42.9%, Android −51.7%).
    • Local iOS/Android HybridApp builds go through Rock (npm run ios / npm run android, remote-build-first with local fallback; force local with -- --local). Pods live in Mobile-Expensify/iOS; the Mapbox token comes from ~/.netrc.

    Navigation architecture notes (established during debugging)

    • Split navigators are one stack, not two panes: the sidebar is route[0], central screens push on top; the side-by-side wide layout is a cardStyle illusion (fixed sidebar width + negative marginLeft).
    • Exactly one route per navigator is focused (state.index, always the top). With sidebar + central visible, the central screen is focused; the sidebar is visible-but-blurred forever. Focus composes up the tree — opening the RHP unfocuses everything under it.
    • Interactivity is orthogonal to focus: the sidebar is clickable because it renders in 'normal' mode without display: none/inert, not because it's focused. A paused sidebar would be visible but dead to clicks — sidebars must always render 'normal', never 'paused'.

    Dev-infra gotcha (cost hours)

    Rspack persistent cache marks node_modules as immutable (managedPaths) — node_modules edits are invisible even across dev-server restarts until the package is in the exception list or node_modules/.cache is deleted. @react-navigation added to the exception list in config/rsbuild/rsbuild.common.ts.

    Pros and cons of the Activity/pause approach

    Pros

    • Large send-message wins on every platform — web −74.6% (626 → 159 ms), Android −51.7% (940 → 453 ms), iOS −42.9% (1289 → 735 ms) — with the optimization living entirely in the navigation layer: no changes to Onyx or to data-consuming components.
    • One model, three platforms: the same inactiveBehavior: 'pauseWhenCovered' value and the same five flagged screens cover web, iOS and Android; all three implementations reduce to the same rule (not focused ∧ not preloaded/dismissing ∧ covered → paused), so the platform difference is confined to which stack implementation reads the option.
    • Eventually-consistent hidden screens: paused screens still update at idle priority, so there's no stale-content flash on return (the weakness of unmount- or freeze-based approaches).
    • State, refs, and DOM survive — form drafts, list positions, and component state all persist through pause (browsers restore scroll across display: none natively; no extra machinery needed).
    • Scoped and declarative: pauseWhenCovered / pauseWhenCovered: false per screen group; easy to reason about which screens pause.
    • Replaces two legacy mechanisms (react-freeze wrappers and the v7 dontDetachScreen patch) with one first-class React primitive.
    • The findings turned into an actual upstream change set (see "Upstream contribution" below), so the patches have a path to disappearing rather than being maintained forever.

    Cons

    • Effect-lifetime semantics change is viral: every []-effect, cleanup-as-close signal, and skip-first-render guard in any pausable screen is a potential bug (four classes found in this PoC — cleanup-as-close, mount-effect re-run, mount-guard inversion, Reanimated flicker; more will exist). This is a codebase-wide audit cost, not a one-time fix.
    • Total render work isn't eliminated, only moved — deferred renders still consume CPU at idle. If idle-time work itself causes jank (low-end devices), numbers may differ.
    • 500ms pause delay: interactions within 500ms of covering a screen still hit an unpaused screen (fast send after opening RHP).
    • Paused screens update lazily, not live. Deferred renders flush only when React gets idle time, so during sustained activity (typing, animations, bursts of Onyx writes) the content under the blur can visibly lag until the main thread quiets down or the screen unpauses. Not frozen — an edit made in the RHP does appear under the blur once idle — but the delay is product-visible.
    • DOM side effects persist while hidden (video/audio keep playing, iframes live) and the keep-visible mechanism amplifies this.
    • Patch maintenance burden: three node_modules patches on alpha packages (core, stack, native-stack) that must be re-ported on every bump, with the pause logic duplicated across two stack implementations that drift independently; upstream may change Activity/heuristic semantics. Plus the forced RNGH 3 upgrade drags its own patch (draggable-flatlist legacy imports) and Legacy* import churn. Mitigated for the two pause patches — regenerated minimal (82 / 68 lines, 6 hunks each), so a bump only conflicts if upstream touches an anchored region.
    • DevTools blindness: profiler barely shows hidden-tree offscreen commits, making paused-screen behavior hard to observe and debug.
    • v8 is alpha: getParent semantics, options merging, and the Activity heuristics may all shift before stable.

    Current state

    Working (verified manually on web): sign-in, Inbox with LHN, Account settings sidebar (interactive), Spend tab, RHP with dim overlay + correct single/wide/super-wide widths, wide RHP survives being covered, scroll preserved across tab switches AND back-navigation. Pausing model: per-screen inactiveBehavior: 'pauseWhenCovered' on five heavy list screens (SCREENS.REPORT, SEARCH.ROOT, and the three report RHP screens), each pausing under ANY cover via the external-cover extension (IsFocusedContext) in both stacks — verified: report chat and Search listings pause under an RHP while staying painted; send-message no longer re-renders them synchronously. No tab-level or navigator-level blanket pauses (flicker / no benefit — see the audit). Reports Search listing pauses cleanly; the Expense listing runs with AnimatedExitRow animations disabled (Reanimated-under-Activity flicker, see failure classes). Native (iOS + Android) builds and runs the same per-screen model via the native-stack patch and RNGH 3.1.0 — measured, not just booted. Measured send-message: web 626 → 159 ms (−74.6%), Android 940 → 453 ms (−51.7%), iOS 1289 → 735 ms (−42.9%). Accordion behavior is stock (no resume guard) — but inactive tab scenes pause via stock bottom-tabs, so the Search-sidebar accordion replay is still reachable on tab switches; retest (see failure classes).

    Open items

    • Deeplink directly to an RHP screen: content below the RHP is missing — the underlying screen (tab/central pane) doesn't render under the overlay when the RHP is the entry point.
    • Proper fix for Reanimated exit/layout animations under pause — shouldApplyAnimation is hard-false in ExpenseFlatSearchView as a stopgap; either gate it on the screen being uncovered (useIsFocused) or fix the 0-rect measurement in the pause display cycle.
    • Audit pausable screens for mount-guard idioms (hasMounted / didMount / isFirstRender / cleanup-as-close) and noisy DOM side effects (video attachments under RHP) — the five flagged screens PLUS everything inside tab scenes (inactive tabs pause via stock bottom-tabs).
    • Retest Search sidebar accordions on tab switches — inactive tab scenes pause via stock bottom-tabs, so the useAccordionAnimation mount-animation replay is still reachable; no guard is in place.
    • React Compiler compliance check on the modified hooks/components (npm run react-compiler-compliance-check check-changed).
    • Typecheck/lint/Jest deliberately skipped (PoC); repo root debug artifacts (PNGs, chain-dump.txt) to clean.
    • Native-specific follow-ups (builds measured, but no regression sweep):
      • Re-check the four effect-lifetime failure classes on native — the pause semantics are identical, so cleanup-as-close, mount-effect re-run and mount-guard inversion are all reachable there too; only the web fixes were verified live.
      • Check whether the Reanimated exit/layout flicker reproduces on native (the web root cause is DOM-rect measurement in the display: none rewrite cycle, which has no native equivalent — if it doesn't reproduce, the shouldApplyAnimation stopgap can stay web-only).
      • Sheet / partial-modal covers now pause (carve-outs removed 2026-07-31). Verified only in jest (effects clean up). On device, check what a paused screen looks like behind a formSheet / iPad modal — it stays painted, but its updates run at idle, so it may visibly lag — and that dismiss/swipe-back off a paused screen behaves. No Expensify screen uses sheetLargestUndimmedDetentIndex today; if one appears, don't flag it (paused ⇒ pointerEvents: 'none').
      • RNGH 3 gesture regression pass on the touched call sites (draggable list reordering, attachment carousel pan/pinch/tap, avatar crop, time picker, onboarding lists).
    • Remove the overlapping react-freeze layer — FreezeWrapper (web tabs) and wrapDescriptorsWithFreeze / freezeNonTopScreens: true (split navigators) still wrap the same screens that now pause; two suspension mechanisms on one tree is a source of confusing behavior and should collapse into <Activity>.

    Upstream contribution (2026-07-31)

    The option was ported into a react-navigation checkout as a PR-ready branch: feat/pause-when-covered in ~/CODE/react-navigation (uncommitted at time of writing, +525/−68 across 8 files).

    What it contains — inactiveBehavior: 'pauseWhenCovered' in all three navigator views, with matching type docs:

    Package File Change
    stack views/Stack/CardStack.tsx static contextType = IsFocusedContext, isCovered flag, one leading 'paused' branch, isVisible clause
    native-stack views/NativeStackView.native.tsx React.use(IsFocusedContext) → isCoveredExternally scene prop, isCovered flag, one leading branch
    native-stack views/NativeStackView.tsx (web) same, so the option isn't a silent no-op in native-stack's web implementation

    Tests (7, all verified green-red-green) — stubbing the pause conditions to false fails exactly these and nothing else:

    Suite Cases
    stack in-stack cover; cover from a parent navigator
    native-stack (native) behind formSheet; behind modal; parent navigator covered; plus a characterization test that default pause keeps both cases active
    native-stack (web) transparentModal cover; parent navigator covered (parent cover transparent, so only the external-cover branch can explain the pause)

    Two tests were rewritten during that pass because they passed with the feature disabled: an opaque in-stack cover (stock already pauses that position in the web native-stack) and an opaque parent cover (the parent screen paused on its own and took the nested effects with it).

    Not upstreamed, deliberately: dontDetachScreen and the core per-layer {web,native} options conversion — both are Expensify-only, carried over from v7. If pauseWhenCovered lands upstream, those two are all that should remain in patches/react-navigation.

    Known limitation to raise in the PR: the external-cover branch can't inspect what covers the navigator — IsFocusedContext is a boolean — so a screen visible behind a parent's sheet pauses. Fixing it properly means carrying more than a boolean in that context, which is the maintainers' call.

    Next steps

    1. Open the upstream PR from feat/pause-when-covered (commit it first): inactiveBehavior: 'pauseWhenCovered' in both stacks, external covers via IsFocusedContext, paused+visible mode, effect-lifetime migration guidance.
    2. Work through the native regression sweep and the react-freeze removal above.

    Links:

    https://www.callstack.com/blog/keeping-screens-visible-with-activity-mode-hidden
    https://reactnavigation.org/blog/2026/03/10/react-navigation-8.0-march-progress#new-inactivebehavior-option-for-all-navigators
    https://docs.swmansion.com/react-native-gesture-handler/docs/guides/upgrading-to-3

  4. LukasMod commented on Aug 3, 2026

    @LukasMod
    Contributor

    @cristipaval I think we can close this investigation and revisit when react navigation 8 will be stable
    @WojtekBoman in case you find this #97477 useful for react navigation bump effort

    TL;DR. Recommendation: don't add the subscribed option to Onyx, fix this in navigation with React
    Navigation 8's pauseWhenCovered, which keeps the complexity in one patch folder instead of in the hook every component uses.

    Next: park the Onyx PRs as drafts, keep the RN8 PoC and the upstream PR open, and re-check when v8 will be stable. Until the migration lands nothing ships for hidden screens, so the remaining send-message work continues on the other fronts (prop stabilization and friends).

    Picking one is close to a one-way door, so "ship A now, switch to B later" is a bad deal. Each option needs its own per-screen review, its own side-effect fixes and its own QA pass, adopting the data-layer one first means paying all of that, then paying it again for the navigation one, and in between unwinding the workarounds written specifically for the first (the catch-up hook, the always-listening opt-outs). Double the work, double the regression surface, on the same screens -> worse than waiting for stable react navigation 8.

    More detailed comparison:

    Stopping hidden screens from re-rendering: two options compared

    The problem in one paragraph

    When you open something on top of a screen (a report over the Search list, a side panel over a report)
    the screen underneath stays alive. It is still listening to the data store, so every write that happens
    while you interact with the top screen makes the hidden screens re-render too. On a heavy account those
    hidden screens are big lists, and the thing you are actually doing (sending a message) waits behind
    their work. That is where the slow 1-2 second send-message spans come from.

    I prototyped two ways to fix it. One works in the data layer (stop the hidden screens from reacting to
    data changes), the other in the navigation layer (let navigation put covered screens to sleep).

    Decision: go with the navigation one. Don't add the data-layer option to Onyx. Wait for React
    Navigation 8, keep the small local patch, and ship it with the migration. Reasoning is at the bottom.


    Option A: data layer, useOnyx({subscribed}) + OnyxFocusBoundary

    The idea. Give useOnyx a switch. When a screen is not focused, its data hooks stop reacting: the
    connection stays open and the data stays warm, but new writes no longer trigger a re-render. When the
    screen comes back into focus, it re-renders once with the newest data.

    To avoid turning that switch on by hand in hundreds of places, one small wrapper (OnyxFocusBoundary)
    sits at the top of a heavy screen and passes "am I focused?" down to every data hook inside it. Wrap the
    screen, everything below it follows. Individual hooks can opt out when they need to keep listening.

    While the switch is off the screen also holds its last shown value, so an unrelated re-render can't
    sneak the new data in and defeat the whole point. The trade is that the dimmed screen genuinely shows
    old data until you go back to it.

    Pros

    • Works today. No navigation upgrade, no alpha libraries, no navigator patches.
    • Small and reversible in the library. About 50 lines in Onyx, off by default, doesn't touch how
      data is stored or written. Behind a Test Tools toggle in the PoC, so it's inert until switched on.
    • Adopt one screen at a time, at whatever granularity fits.
    • Nothing is torn down. No cleanup runs, so effects, timers and subscriptions on the hidden screen
      keep working, the screen just stops re-rendering. The whole class of "my once-on-mount code ran
      again" bugs that the sleep approach creates doesn't exist here. (When data arrives still changes,
      though, see the adoption cost below.)
    • Covers cases navigation can't see. Sidebars that stay visible while unfocused, screens that must
      stay clickable, and anywhere else where "covered" isn't something navigation knows about.
    • Better than the freezing already in the app. The current freeze mechanism can't touch a screen
      that is blurred but still visible under a panel, and on mobile it always keeps the screen right below
      the top one alive for the back gesture, exactly the heavy one that matters here.

    Cons

    • Only stops re-renders. Everything else on the hidden screen keeps running.
    • Hidden screens show stale content until you return to them.
    • It does require component changes, see below. Wrapping the screen is not the whole job.
    • Leaks around the edges. A handful of components import Onyx directly and skip the wrapper, and
      anything rendered through a portal escapes it too.
    • Permanent complexity in the layer everyone touches. Every future contributor has to know the
      switch exists, what it does, and when not to use it.

    What adopting one screen actually cost (PR #96471, 12 files, +160 / −11)

    The "wrap the screen and you're done" description is too optimistic. Breaking the PoC down:

    • One-time infrastructure (~85 lines): the boundary component in web and native variants, its
      context, the wiring in the app's useOnyx wrapper, plus a dev toggle so the feature can be A/B'd.
    • Per-screen wiring: wrap the screen, and pin one key back to always-listening because its cleanup
      logic only runs while the screen is hidden.
    • A real behavior fix inside a component. Gating changes when data arrives: writes that used to
      land one by one while the screen was hidden now arrive together the moment it comes back. That broke
      the unread-message marker on the report list, because new messages were treated as "arrived while you
      were watching", so the marker was suppressed and later swallowed. Fixing it needed a new
      useFocusCatchUpTime hook and two extra branches in MoneyRequestReportActionsList to tell
      catch-up deliveries apart from live ones.
    • The −68% figure assumes more of this work, on the Spend Reports tab, that isn't in the PR.

    None of this is unmanageable, but it means adoption is "review and fix the screen", not "wrap it". It's
    the same kind of per-screen cost the navigation option has, with a different failure mode (data arriving
    in a batch instead of effects re-running) and a similar amount of work.

    Numbers (heavy account, one screen wrapped)

    Scenario Web iOS / Android
    Send a message over the Search money-report page 854 → 523 ms (−39%) 1637 → 1039 ms (−36%)
    Same, plus stabilizing the Spend Reports tab (what the feature could reach) 829 → 265 ms (−68%) —
    Open a report from that page in the side panel 1502 → 997 ms (−34%) 3024 → 3108 ms (+2.8% / ~0%)

    Option B: navigation layer, React Navigation 8 pauseWhenCovered

    The idea. React Navigation 8 can put a covered screen to sleep using React's new <Activity>
    feature. A sleeping screen keeps its state, its scroll position and its pixels on screen, but its data
    subscriptions are dropped and any work it still needs to do happens later, when the app is idle, not in
    the middle of user interaction.

    The catch: out of the box, v8 refuses to sleep exactly the screens that matter here. It always keeps a
    screen awake when something transparent is on top of it (the side panel) or when it is the second from
    the top, and it can't see a panel opened by a different navigator at all. So I added a small patch: an
    extra option a screen can opt into that says "sleep whenever anything covers me, wherever that cover
    comes from". It is turned on for five heavy list screens.

    Pros

    • The biggest wins, on all three platforms, with no changes to Onyx and no changes to the
      components reading data. The fix lives entirely in navigation.
    • Stops all the work, not just rendering. The sleeping screen unsubscribes instead of quietly
      filtering updates.
    • Same solution everywhere. One option, five screens, identical behavior on web, iOS and Android.
    • Nothing is deliberately held back. Unlike the data-layer option, a sleeping screen never refuses
      new data, any render that reaches it reads the current value. That's why edits made in the panel
      usually do show up under the blur. It just has nobody pushing it, which has its own consequences,
      see the cons.
    • Nothing to remember for contributors. It's a screen setting, not something every hook author has
      to think about.
    • Retires the freeze wrappers. Sleeping does the same job better, so the react-freeze layer
      wrapping screens today can go.

    Cons

    • It can't ship yet. v8 is still alpha and the app hasn't migrated. It also forces a gesture-handler
      major upgrade.
    • Sleeping runs cleanup code. React treats "asleep" like "unmounted" for effects, so anything
      written as "run once when I appear" or "do X when I go away" fires at the wrong time. I already hit
      four of these (a panel collapsing itself, a chat jumping to the bottom, an animation replaying, list
      row animations flickering). Finding the rest is a codebase-wide pass.
    • Patches on alpha packages need maintaining until upstream catches up.
    • Half-second delay before a covered screen actually falls asleep, so a very fast interaction still
      hits it awake.
    • Content under the blur can lag, or not update at all. Three cases, in decreasing likelihood:
      a render reaches it but runs at low priority, so it trails during sustained activity and catches up
      when the main thread quiets; nothing renders it, so it stays exactly as it was until it wakes; or
      a render reaches it but Onyx's shared per-key snapshot cache, only invalidated by live subscribers,
      hands it the old value anyway, possible when the sleeping screen was the sole reader of that key.
      The last one is unmeasured and worth checking on resume.
    • Hard to observe. The React profiler barely shows what a sleeping screen does.

    Numbers (heavy account, send a message: Spend → report panel → report)

    Platform Before After Change
    Web 626 ms 159 ms −74.6%
    Android 940 ms 453 ms −51.7%
    iOS 1289 ms 735 ms −42.9%

    What React Navigation's maintainer said

    I proposed the option upstream (PR #13200).
    Maintainer answer, in short:

    • Not as a public option, not yet. The current mechanism is a bit of a hack internally, and exposing
      a knob would lock them into it. Something similar may be exposed later.
    • Keep a small local patch for this specific case instead.
    • He wants to improve the built-in behavior anyway

    One caveat about the numbers

    The two sets were measured on different days. Both are large wins on the same kind of scenario, but they are not a clean head-to-head. A same-day A/B on one
    flow was never run.


    Why I picked the navigation one

    Both fix the same symptom. The difference is what's left to live with afterwards.

    • The data-layer option buys a win but leaves permanent complexity in the layer every single
      component touches: a new option on the most-used hook in the app, a wrapper component
    • Per-screen adoption cost is roughly a wash. Both need a review-and-fix pass on every screen being
      optimized.
    • The navigation option buys a bigger win, and its cost is concentrated in one patch folder. If upstream improves the built-in behavior, the patch shrinks
      or disappears. It also keeps a navigation problem inside the navigation layer.

    There is also a behavior difference worth naming, and it's subtler than "one is fresher". Neither
    approach re-renders a hidden screen on an ordinary write. The difference is what happens when something
    else causes it to render: a sleeping screen tries to read the current data, a frozen screen
    deliberately returns its last value. So sleeping can drift back into sync on its own (deferred call),
    and in this app it usually does, because context changes reach those screens, while freezing is stale by
    design until you return. For content still visible behind a dimmed overlay, that makes sleeping the
    better default. Not a decisive gap, but it points the same way as everything else.

    What happens next

    1. Park the Onyx work. Leave PR #808 and
      [WIP] Stabilize MoneyRequestReport - v3 #96471. Don't merge the option, don't wrap more screens. The
      investigation stays useful if render-only gating is ever needed for something navigation can't reach.
    2. Keep the navigation PoC. Keep App PR #97477
      so it can be useful for migration from rn7 to rn8, and leave the upstream PR open as the written record of the design.
    3. Watch each v8 alpha. If the built-in improvements land, the patch may not be needed at all.
    4. Accept the gap in the meantime. Nothing ships for hidden screens until the migration, so the
      remaining send-message work continues on the other fronts (prop stabilization etc).

    Links

    Where this is tracked

    • App#95584: the remaining 1-2 s send-message spans, both tracks started here
    • App#97081: explore a navigation-layer solution (Option B)

    Option A, data layer (being parked)

    Option B, navigation layer (the recommended direction)

    Background reading

  5. LukasMod commented on Aug 3, 2026

    @LukasMod
    Contributor

    Custom implementation without migration to RN8 already in progress, very similar to RN8 alpha ActivityView: #97666
    Discussion in a slack: https://callstack-hq.slack.com/archives/C08CZDJFJ77/p1785758333891079

  6. LukasMod commented on Aug 5, 2026

    @LukasMod
    Contributor

    @cristipaval I think we can close this issue for now:

  7. cristipaval commented on Aug 10, 2026

    @cristipaval
    ContributorAuthor

    Thanks @LukasMod 🙏

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

Metadata

Metadata

Assignees

Labels

Weekly

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions