[Due for payment 2026-11-28] [$175] [Metrics] Native tab bar re-renders every tab when an RHP opens, slowing Create expense on mobile
Problem
Since 9.5.13, the Create expense flow opens slower on iOS and Android. The Starting Create expense flow metric went from 264ms to 352ms (+33%) in production. The target is 400ms.
| Platform | Before | After |
|---|---|---|
| iOS | 311ms | 394ms |
| Android | 524ms | 666ms |
| Windows, Mac | no change | no change |
On iOS the jump lands exactly at 9.5.13 (349ms → 429ms). Search, Send message and Open report slowed down in the same release.
Cause
The regression comes from https://github.com/Expensify/App/pull/101339, which added the native liquid glass tab bar. It is the only native change in 9.5.13. On a local iOS dev build, the Create expense span went from 218ms to 283ms (about 30% slower) between the commit before and the commit after that PR.
When a flow opens a right hand panel (RHP), the app hides the native tab bar. That change re-renders the whole tab navigator. Every tab rebuilds its options and its icon, and the hidden tabs render in the same commit as the navigation. The old JS tab bar avoided this with lazy: true and freezeOnBlur: true.
What we already know
- Freezing the hidden tabs does not move the metric. This was tested on a device.
- Wrapping each native tab in
react-freezeshows a blank screen for 6 to 92 frames on every tab switch, because the native bar switches the view before React can unfreeze it. That attempt is in commit92918cfd3a9, reverted in43a71c08380. lazy: truedoes not work with the native bar. A lazy tab gives the bar an empty container, so all tabs mount up front and keep rendering on Onyx updates.- Reverting https://github.com/Expensify/App/pull/101339 is not an option. The fix needs to work with the native bar.
Code pointers
- The tab bar visibility: useNativeTabNavigator.ts#L56
- The visibility goes into the options that every tab shares: index.ios.ts#L54, index.android.ts#L39
- Each tab builds its icon from those options: index.ios.ts#L60-L76
- The tab navigator merges them per tab on every render: TabNavigator.native.tsx#L41-L49
Expected outcome
- Hiding or showing the native tab bar does not re-render the tab screens or rebuild the icons of every tab.
- The Create expense metric on iOS and Android goes back to its 9.5.12 level.
- Search, Send message and Open report recover in the same way.
Context
- Slack discussion: https://expensify.slack.com/archives/C05LX9D6E07/p1793381005323199?thread_ts=1793053361.338919&cid=C05LX9D6E07
- Create expense metrics issue: https://github.com/Expensify/App/issues/81849
- Liquid glass follow up tracker: https://github.com/Expensify/App/issues/104197
cc @sumo-slonik, who offered to help review a fix that works with the native bar.
Issue Owner
Current Issue Owner: @mallenexpensifyUpwork Automation - Do Not Edit
- Upwork Job URL: https://www.upwork.com/jobs/~022116228658276106794
- Upwork Job ID: 2116228658276106794
- Last Price Increase: 2026-10-30
Proposal
⚠️ Medium confidence. The code supports this, but I did not profile it on a device. One part of the issue's premise looks wrong; see the first section.
What is the root cause of that problem?
Opening an RHP does not change tab bar visibility. shouldShowNativeTabBar reads only the tab navigator's own state (useNativeTabNavigator.ts:54-56). The RHP is pushed onto the root stack next to the tab navigator, not inside it. Visibility flips when you navigate inside a tab, for example when you open a report from Inbox. That would explain "Open report" and "Search", but not "Create expense" directly.
What an RHP open does change: isFocusedRouteTabRoot (L49) goes from true to false. That re-renders TabNavigator inside the navigation commit, and the effect at L73-78 calls setOptions on the root stack, which re-renders the root navigator. tabState (L54) also re-renders TabNavigator on every push or pop inside any tab.
Why a navigator re-render is expensive here:
- Visibility sits in the
screenOptionsthat every tab shares (index.ios.ts:54, index.android.ts:39). getScreenOptions(TabNavigator.native.tsx:41-48) gets a new identity whenever those options change. React Navigation'suseDescriptorsthen rebuilds all 6 descriptors, andNativeBottomTabViewre-renders 6Tabs.Screenelements with new appearance objects and icons.- The tab screen components themselves do not re-render.
SceneViewwraps them inStaticContainer, so the cost is in the navigator layers. - Icons are not redrawn, because
getTabIconcaches them (tabIconRasterizer.ts:202-215). ButgetTabBarIconreturns a new closure on each call (L221).
How the native bar reads visibility: NativeBottomTabView reads it only from the focused tab's tabBarStyle.display and passes it to the single tabBarHidden prop on Tabs.Host from react-native-screens. Visibility is one prop, but today it costs a full options rebuild.
What changes do you think we should make in order to solve the problem?
- Take visibility out of the shared options. Remove
displayfromtabBarStylein bothuseNativeTabBarOptionsfiles and drop theshouldShowNativeTabBarparam. KeepbackgroundColor, because iOS 18 and earlier still need it. The per-tab options then change only when the theme, labels, dots or layout change. - Send visibility on its own path. Compute
shouldShowNativeTabBarinto a small store that updates synchronously. Add a@react-navigation/bottom-tabspatch soNativeBottomTabViewrenders a thin wrapper aroundTabs.Host. The wrapper readstabBarHiddenwithuseSyncExternalStore. Because the wrapper passeschildrenthrough unchanged, a visibility toggle re-renders only the wrapper and sends one native prop update. Patches 003-005 already changeNativeBottomTabView, so this follows existing practice. - Point
NativeTabBarOverlayat the same store. It reads visibility fromdescriptors[...].options.tabBarStyletoday (NativeTabBarOverlay.tsx:43). This keeps the floating buttons in sync with the bar in the same frame. - Keep
TabNavigatorfrom re-rendering on unrelated navigation. Move theisFocusedRouteTabRoot/gestureEnabledeffect and thetabState-derived values (L49, L54-59, L80-85) into a child component that renders nothing. Then an RHP open no longer re-renders<Tab.Navigator>. This step targets "Create expense" directly.
Before you start, confirm the cost with a React Profiler run of "Create expense" on device. Check whether TabNavigator and NativeBottomTabView re-render in the RHP-open commit. Also run the React Compiler check on TabNavigator.native.tsx, useNativeTabNavigator.ts and useNativeTabBarOptions/*. I couldn't run either one here. If those files do not compile, every flip at L49 rebuilds all descriptors, and step 4 matters most.
What alternative solutions did you explore? (Optional)
navigation.setOptionson the focused tab only, with no patch. This avoids a new patch, but it still re-renders the tab navigator and all 6 descriptors. It also needs every tab to carry the right flag at the moment of a tab switch, because the native bar reads visibility from whichever tab has focus.- Memoize per-route options inside
getScreenOptions. This does not help, becauseuseDescriptorsmerges into a fresh object on every navigator render anyway. - Separate cause to rule out: all tabs mount up front, so every tab re-renders on its own Onyx updates. You already found that freezing hidden tabs did not move the metric, so this is probably not the main cause.
Related: [Liquid Glass] Follow Up Tracker, Add liquid glass bottom tab bar to iOS, Android and mWeb
Next Steps for Contributor+ team:
To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/105517) to create a draft PR.
To refine: @MelvinBot <your feedback>
To reject: Explain why you are rejecting Melvin's proposal.
Triggered auto assignment to Contributor-plus team member for initial proposal review - @nyomanjyotisa (External)
Job added to Upwork: https://www.upwork.com/jobs/~022116228658276106794
Proposal for Issue #105517: [Metrics] Native tab bar re-renders every tab when an RHP opens, slowing Create expense on mobile
Proposal
Please re-state the problem that we are trying to solve in this issue.
Opening the Create expense flow (or any flow that mounts a Right-Hand Panel (RHP)) on iOS and Android exhibits a significant latency regression (+33% slower, jumping from 264ms to 352ms in production, and up to 666ms on Android).
What is the root cause of that problem?
When an RHP opens:
- In
useNativeTabNavigator.ts,isTabRouteAtRoot(activeTabRoute)transitions tofalsebecause an RHP route is now focused. - This toggles
shouldShowNativeTabBarfromtruetofalse. - In
TabNavigator.native.tsx:const {screenOptions, getTabOptions} = useNativeTabBarOptions({shouldShowNativeTabBar, isAccountAvatarShown, dotColors, tabLabels}); const getScreenOptions = ({route}: {route: {name: NativeTabName}}) => ...- In
useNativeTabBarOptions/index.ios.tsandindex.android.ts, changingshouldShowNativeTabBarreconstructsscreenOptionswithtabBarStyle: {display: shouldShowNativeTabBar ? 'flex' : 'none', ...}. - Crucially,
getScreenOptionsis an un-memoized inline function passed directly to<Tab.Navigator screenOptions={getScreenOptions}>. - On the visibility toggle,
getTabOptionsis invoked for every single tab (HOME,REPORTS_SPLIT_NAVIGATOR,SEARCH_FULLSCREEN_NAVIGATOR,INSIGHTS,WORKSPACE_NAVIGATOR,SETTINGS_SPLIT_NAVIGATOR). - For every tab on iOS,
getTabBarIcon(...)rasterizes/regenerates new icon descriptors, labels, font-scaling calculations, and dimensions in the exact same React commit as the heavy RHP transition. - Because tab options change simultaneously across all tabs on the navigator level,
@react-navigation/bottom-tabsrecalculates options and re-renders descriptors across the entire tab hierarchy rather than performing a lightweight visibility update on the native bar container.
- In
What changes do you think we should make in order to solve the problem?
-
Decouple Tab Bar Visibility from Per-Tab Options Recreation: Instead of mutating
screenOptions.tabBarStyle(which triggers descriptor rebuilds for all tab routes ingetScreenOptions), separate bar visibility from the individual tab screen descriptors.- In
useNativeTabBarOptions, memoizegetTabOptionsandscreenOptionswithuseCallback/useMemoso individual tab options (icons, rasterized glyphs, labels) are strictly stable and referentially cached across visibility changes. - Pass
tabBarStyleupdates directly via the layout container (NativeTabLayout.tsx) or control the native bottom tab bar visibility viatabBarVisibility/ native controller visibility property without re-evaluatingtabBarIconfor inactive tabs.
- In
-
Memoize
getScreenOptionsinTabNavigator.native.tsx: WrapgetScreenOptionsinuseCallbackdepending strictly on stable getters:const getScreenOptions = useCallback( ({route}: {route: {name: NativeTabName}}) => { if (route.name === tabWithoutBarItem) { return {...screenOptions, ...HIDDEN_TAB_OPTIONS}; } return { ...screenOptions, ...getTabOptions(route.name), tabBarSelectionEnabled: isTabSelectionEnabled(route.name), }; }, [screenOptions, tabWithoutBarItem, getTabOptions, isTabSelectionEnabled] ); -
Cache Icon Rasterization: In
tabIconRasterizer.ts, ensure that icon generator callbacks returned bygetTabBarIconare referentially memoized per tab name and state so they do not recreate canvas/image descriptors during navigator layout transitions when only bar visibility changes.
What alternative solutions did you explore? (Optional)
- As noted in the issue, wrapping tabs in
react-freezecauses noticeable blank frames (6 to 92 frames) due to race conditions with native view switching. - Retaining
display: 'none'only on the outer native bar view container (NativeTabLayout) rather than re-evaluating each route descriptor preserves native bar hiding while completely eliminating the multi-tab re-render cascade in the RHP opening commit.
Contributor details:
- Contributor: @apoorv-xs
- Upwork Profile: In review / ready for direct offer
- Availability: Immediate (40+ hrs/wk)
@nyomanjyotisa @joekaufmanexpensify Friendly check-in on the initial proposal review for #105517. The local reproduction and memoization fix are fully mapped in the branch and ready to submit as a clean PR as soon as the Upwork contract offer is issued.
@MelvinBot I profiled Create expense on iOS and Android. The native tab view/screens didn’t re-render, and Android’s tabBarHidden stayed false when it opened. Extracting the root-focus subscription removed one small render but showed no consistent speedup. Could you update the root-cause section to explain the slowdown in this flow and tag me when it’s ready?
@nyomanjyotisa the root-cause section is updated below. Your profile rules out the tab options theory from my earlier proposal. Please disregard its fix steps 1–4.
Updated root cause
⚠️ Medium-low confidence. I traced this in the code, but nothing has been measured yet. The A/B test at the end decides it.
What is the root cause of that problem?
The cost is not in React renders. It comes from the hidden tabs that now stay mounted, and from the native work they cause.
- All 6 tabs mount at startup and are never unmounted. The old JS tab bar used
lazy: true, so a tab you never opened was never mounted. Add liquid glass bottom tab bar to iOS, Android and mWeb dropped that for the native bar (FreezeWrapper/index.native.tsx, useHasTabBeenShown.ts). Spend, Insights, Workspaces and Settings are now always mounted. - Hidden tabs run loading-bar animations that change layout every frame.
LoadingBarloopswithRepeatonleftandwidth(LoadingBar.tsx:19-68). Those are layout props, so each frame triggers a Fabric shadow-tree commit and a layout pass.- Spend shows the bar while its data is not loaded (SearchPageNarrow/index.tsx:271-285). A Spend tab you never opened never requests a search (SearchPage.tsx:60-63). If no cached snapshot exists, its bar can loop indefinitely in the background.
- The bars on Inbox, Settings and Workspaces show while
OpenApp,ReconnectApp,OpenReportorReadNewestActionis in flight (useInFlightRequests.ts:52, L272-278). Every mounted tab now animates during those requests. That fits Open report and Send message slowing down too.
- Every React commit costs more on native. For example, the RHP push that starts Create expense is a commit. Reanimated's commit hook runs inside each Fabric commit (
ReanimatedCommitHook.cpp). It re-applies the latest props of every animated view that is still mounted, so the views in hidden tabs add to its work. That shadow-tree work, plus layout over a much bigger tree, would explain the pattern:- The span grows.
- The React Profiler shows no tab or screen re-renders, because it doesn't see this work.
- Freezing doesn't help, because frozen views stay mounted.
- Only iOS and Android regress.
What I ruled out:
- Onyx subscribers in hidden tabs. Create expense only writes the small
TRANSACTION_DRAFTcollection (clearMoneyRequest/initMoneyRequest), and those selectors take microseconds. - Navigation-state hooks added by that PR. They cost under 1 ms per navigation.
- Tab bar visibility. It doesn't change in this flow, as your profile showed.
How to confirm (cheap A/B)
- Pass
shouldShow={false}toLoadingBarwhenever its tab isn't focused, then re-measure Create expense. If the span drops, cause 2 is confirmed. - If it doesn't drop, render only a placeholder for tab contents until
useHasTabBeenShownturns true. Freezing is not enough; the contents must be unmounted. If the span drops then, the cause is the mounted-tree cost in cause 3 rather than the animations. - Optionally, capture a Perfetto (Android) or Instruments (iOS) trace and compare the shadow-tree commit and layout time inside the span window, before and after #101339.
What changes do you think we should make in order to solve the problem?
This depends on which step of the A/B moves the metric:
- If step 1 moves it: gate
LoadingBarand any other looping animation in tab roots on tab focus. Also consider animating the bar withtransforminstead ofleft/width, so it no longer triggers layout. - If step 2 moves it: mount each tab's heavy contents only after the tab is first shown. This stays compatible with the native bar, because the bar still gets a non-empty container.
Next Steps for Contributor+ team:
To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/105517) to create a draft PR.
To refine: @MelvinBot <your feedback>
To reject: Explain why you are rejecting Melvin's proposal.
Proposal
Please re-state the problem that we are trying to solve.
On mobile devices (iOS and Android), tapping "Create expense" (or opening any Right Hand Pane / RHP modal) causes the native tab bar and every single mounted tab screen to unnecessarily re-render simultaneously. Because background tabs on native are not frozen, this concurrent re-rendering floods the JavaScript thread during the transition, causing severe frame drops, UI lag, and slowed interaction metrics (INP) when opening the Create Expense flow.
What is the root cause of that problem?
In src/libs/Navigation/AppNavigator/Navigators/NativeTabNavigator/useNativeTabNavigator.ts (lines 58 and 87–92):
const isFocusedRouteTabRoot = useNavigationState((state) => TAB_ROOT_SCREENS_WITHOUT_GESTURE.has(findFocusedRoute(state)?.name ?? ''));
...
useEffect(() => {
if (!shouldUseNarrowLayout || !parentNavigation) {
return;
}
parentNavigation.setOptions({gestureEnabled: !isFocusedRouteTabRoot});
}, [isFocusedRouteTabRoot, shouldUseNarrowLayout, parentNavigation]);
-
Root Navigation State Subscription in Hook Body:
useNavigationState((state) => ...)insideuseNativeTabNavigatorsubscribes directly to root navigation state changes. When a user opens Create Expense,NAVIGATORS.RIGHT_MODAL_NAVIGATORis pushed onto the root stack, andfindFocusedRoute(state)shifts from the active tab root screen (e.g.ReportsorHome) to the newly pushed RHP screen (e.g.IOURequestStepAmount). As a result,isFocusedRouteTabRoottransitions fromtruetofalse. -
Cascading Re-render of
TabNavigator: BecauseisFocusedRouteTabRootchanges value insideuseNativeTabNavigator, the hook triggers a re-render ofTabNavigatorinsrc/libs/Navigation/AppNavigator/Navigators/TabNavigator.native.tsx. -
Re-creation of Screen Options & Tab Icons: When
TabNavigatorre-renders,getScreenOptions(lines 41–48) re-runs and callsgetTabOptionsfromuseNativeTabBarOptions, which callsgetTabBarIconto generate new icon callbacks and freshoptionsdescriptor objects for all six tabs (Home,ReportsSplitNavigator,SearchFullscreenNavigator,Insights,WorkspaceNavigator, andSettingsSplitNavigator). -
Re-rendering of All Tabs in
NativeBottomTabView: In@react-navigation/bottom-tabs/unstable,NativeBottomTabViewobserves new descriptor options for every route instate.routes. In its render loop:<Deferred lazy={lazy} visible={isFocused || isPreloaded}> <ScreenWithHeader isFocused={isFocused} route={route} navigation={navigation} options={options}> <NavigationMetaContext.Provider value={meta}> {render()} </NavigationMetaContext.Provider> </ScreenWithHeader> </Deferred>Because
optionsanddescriptorschanged,{render()}is re-executed for every mounted tab. SinceFreezeWrapperon native is a no-op (return children;) to preserve instantaneous native tab switching without white flashes, all six tab component trees re-render simultaneously on the JavaScript thread while the Create Expense RHP is attempting to open and animate.
What changes do you think we should make in order to solve the problem?
-
Decouple the gesture management into an isolated component: Extract
isFocusedRouteTabRootand theparentNavigation.setOptions({gestureEnabled: !isFocusedRouteTabRoot})side-effect out ofuseNativeTabNavigatorand into a dedicatedTabSwipeBackGesturecomponent rendered insideNativeTabLayout(or alongsideTab.Navigator). This isolates the root navigation state subscription so that opening/closing an RHP only updatesparentNavigation's gesture setting without triggering a re-render ofuseNativeTabNavigatororTabNavigator. -
Clean up
useNativeTabNavigator.ts: RemoveisFocusedRouteTabRootand its associateduseEffectfromuseNativeTabNavigator.ts.
src/libs/Navigation/AppNavigator/Navigators/NativeTabNavigator/TabSwipeBackGesture.tsx (New file)
import useResponsiveLayout from '@hooks/useResponsiveLayout';
import SCREENS from '@src/SCREENS';
import {findFocusedRoute, useNavigation, useNavigationState} from '@react-navigation/native';
import {useEffect} from 'react';
const TAB_ROOT_SCREENS_WITHOUT_GESTURE = new Set<string>([SCREENS.HOME, SCREENS.INBOX, SCREENS.SEARCH.ROOT, SCREENS.INSIGHTS, SCREENS.SETTINGS.ROOT]);
function TabSwipeBackGesture() {
const {shouldUseNarrowLayout} = useResponsiveLayout();
const navigation = useNavigation();
const parentNavigation = navigation.getParent();
const isFocusedRouteTabRoot = useNavigationState((state) => TAB_ROOT_SCREENS_WITHOUT_GESTURE.has(findFocusedRoute(state)?.name ?? ''));
useEffect(() => {
if (!shouldUseNarrowLayout || !parentNavigation) {
return;
}
parentNavigation.setOptions({gestureEnabled: !isFocusedRouteTabRoot});
}, [isFocusedRouteTabRoot, shouldUseNarrowLayout, parentNavigation]);
return null;
}
export default TabSwipeBackGesture;
src/libs/Navigation/AppNavigator/Navigators/NativeTabNavigator/useNativeTabNavigator.ts
--- a/src/libs/Navigation/AppNavigator/Navigators/NativeTabNavigator/useNativeTabNavigator.ts
+++ b/src/libs/Navigation/AppNavigator/Navigators/NativeTabNavigator/useNativeTabNavigator.ts
@@ -32,13 +32,6 @@ import {isInboxTabAtChatList, isNativeTabSelectionEnabled} from './tabScreenList
import useIsWorkspacesTabRestored from './useIsWorkspacesTabRestored';
-/**
- * Root-level tab screens where the swipe-back gesture should be disabled.
- * Swiping from these screens would pop the entire TAB_NAVIGATOR, which feels wrong.
- * WORKSPACE.INITIAL is intentionally excluded, since swiping back from it returns to the workspace list.
- */
-const TAB_ROOT_SCREENS_WITHOUT_GESTURE = new Set<string>([SCREENS.HOME, SCREENS.INBOX, SCREENS.SEARCH.ROOT, SCREENS.INSIGHTS, SCREENS.SETTINGS.ROOT]);
-
/** stale === false distinguishes a fully realized NavigationState from a PartialState. */
function isRealizedNavigationState(state: NavigationState | PartialState<NavigationState> | undefined): state is NavigationState {
return state?.stale === false;
@@ -54,9 +47,6 @@ function useNativeTabNavigator() {
const {indicatorColor: workspacesIndicatorColor, status: workspacesIndicatorStatus} = useWorkspacesTabIndicatorStatus();
const {indicatorColor: accountIndicatorColor, status: accountIndicatorStatus} = useAccountTabIndicatorStatus();
const navigation = useNavigation();
- const parentNavigation = navigation.getParent();
- const isFocusedRouteTabRoot = useNavigationState((state) => TAB_ROOT_SCREENS_WITHOUT_GESTURE.has(findFocusedRoute(state)?.name ?? ''));
const route = useRoute();
// The Tab.Navigator's own state lives at `parentState.routes[i].state`. We can't read it via
// `useNavigationState((s) => s)` here because the navigator's body runs before <Tab.Navigator>
@@ -86,13 +76,6 @@ function useNativeTabNavigator() {
[NAVIGATORS.SETTINGS_SPLIT_NAVIGATOR]: translate('initialSettingsPage.account'),
};
- useEffect(() => {
- if (!shouldUseNarrowLayout || !parentNavigation) {
- return;
- }
- parentNavigation.setOptions({gestureEnabled: !isFocusedRouteTabRoot});
- }, [isFocusedRouteTabRoot, shouldUseNarrowLayout, parentNavigation]);
-
useEffect(() => {
if (!isRealizedNavigationState(tabState)) {
return;
src/libs/Navigation/AppNavigator/Navigators/NativeTabNavigator/NativeTabLayout.tsx
--- a/src/libs/Navigation/AppNavigator/Navigators/NativeTabNavigator/NativeTabLayout.tsx
+++ b/src/libs/Navigation/AppNavigator/Navigators/NativeTabNavigator/NativeTabLayout.tsx
@@ -10,6 +10,7 @@ import React from 'react';
import {View} from 'react-native';
import NativeTabBarOverlay from './NativeTabBarOverlay';
+import TabSwipeBackGesture from './TabSwipeBackGesture';
import TabPressListeners from './TabPressListeners';
type NativeTabLayoutProps = Parameters<NonNullable<NativeBottomTabNavigatorProps['layout']>>[0];
@@ -39,6 +40,7 @@ function NativeTabLayout({children, state, descriptors}: NativeTabLayoutProps)
state={state}
descriptors={descriptors}
/>
+ <TabSwipeBackGesture />
{shouldUseNarrowLayout && (
<NativeTabBarOverlay
state={state}
Similarly, the same TabSwipeBackGesture component can be used in web TabNavigator.tsx (lines 110–117) to prevent redundant re-renders on web when an RHP opens.
What alternative solutions did you explore? (Optional)
- Freezing background tabs on native (
freezeOnBlur: true): As documented inFreezeWrapper/index.native.tsx, freezing background tabs on native causes an empty/white screen flicker during instant native tab transitions before React unfreezes the screen. - Wrapping all individual tab navigators in
React.memo:React.memowould violate Expensify's React Compiler rules and would not prevent theuseNativeTabNavigatorhook andTabNavigatorcontainer from needlessly re-executinguseNativeTabBarOptionsand icon rasterization. Decoupling the navigation state subscription solves the root cause at the source.
Automated Tests
Add a unit test in tests/unit/TabSwipeBackGestureTest.tsx (or tests/unit/useNativeTabNavigatorTest.ts):
import {renderHook} from '@testing-library/react-native';
import TabSwipeBackGesture from '@libs/Navigation/AppNavigator/Navigators/NativeTabNavigator/TabSwipeBackGesture';
import useNativeTabNavigator from '@libs/Navigation/AppNavigator/Navigators/NativeTabNavigator/useNativeTabNavigator';
import NAVIGATORS from '@src/NAVIGATORS';
import SCREENS from '@src/SCREENS';
describe('TabNavigator render stability on RHP open', () => {
it('does not re-render useNativeTabNavigator when an RHP route opens over tabs', () => {
// Given the native tab navigator mounted with the Home tab focused
let renderCount = 0;
const mockNavigationState = {
routes: [
{key: 'tab-nav', name: NAVIGATORS.TAB_NAVIGATOR, state: {index: 0, routes: [{name: SCREENS.HOME}]}},
],
};
const {rerender} = renderHook(() => {
renderCount++;
return useNativeTabNavigator();
});
expect(renderCount).toBe(1);
// When a Right Modal Navigator (RHP) route is pushed to root navigation state
mockNavigationState.routes.push({
key: 'rhp-nav',
name: NAVIGATORS.RIGHT_MODAL_NAVIGATOR,
state: {index: 0, routes: [{name: SCREENS.MONEY_REQUEST.CREATE}]},
} as any);
rerender({});
// Then useNativeTabNavigator should not re-render, preventing all tabs from re-rendering
expect(renderCount).toBe(1);
});
});
Contributor details
Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~014bb7d4c250a1fe03
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0105ac9050d5ca10e5
Proposal
What is the root cause of that problem?
In src/libs/Navigation/AppNavigator/Navigators/NativeTabNavigator/useNativeTabNavigator.ts:49, isFocusedRouteTabRoot subscribes to the root navigation state via useNavigationState:
const isFocusedRouteTabRoot = useNavigationState((state) => TAB_ROOT_SCREENS_WITHOUT_GESTURE.has(findFocusedRoute(state)?.name ?? ''));
When an RHP (Right Hand Panel / modal, e.g. "Create expense", "Search", or report details) is opened, the RHP is pushed onto the root stack above the tab navigator. This root state transition flips isFocusedRouteTabRoot from true to false.
Because this subscription lives inside useNativeTabNavigator, the state transition forces TabNavigator (src/libs/Navigation/AppNavigator/Navigators/TabNavigator.native.tsx) to re-render in the same commit as the RHP open. During that re-render:
useNativeTabBarOptionsrecreatesscreenOptionsandgetTabOptions.getScreenOptionsproduces new function references on every render.- React Navigation's descriptor cache invalidates, forcing all 6 tab descriptors to rebuild and re-evaluating each
Tab.Screen. - On mobile devices (particularly Android and lower-spec iOS devices), this synchronous descriptor rebuild stalls the JS thread, producing an observable delay when opening the Create Expense flow.
However, isFocusedRouteTabRoot is only consumed by a single side-effect in useNativeTabNavigator.ts:73-78:
useEffect(() => {
if (!shouldUseNarrowLayout || !parentNavigation) {
return;
}
parentNavigation.setOptions({gestureEnabled: !isFocusedRouteTabRoot});
}, [isFocusedRouteTabRoot, shouldUseNarrowLayout, parentNavigation]);
It is not returned by useNativeTabNavigator and has no visual effect on the tab bar itself.
What changes do you think we should make in order to solve the problem?
-
Extract the gesture-control side effect into an isolated component:
- Create a lightweight child component (e.g.
TabSwipeBackGestureController) that houses theisFocusedRouteTabRootuseNavigationStateselector and theparentNavigation.setOptions({gestureEnabled: !isFocusedRouteTabRoot})effect. - Render
TabSwipeBackGestureControllerinsideNativeTabLayout(src/libs/Navigation/AppNavigator/Navigators/NativeTabNavigator/NativeTabLayout.tsx). - Remove
isFocusedRouteTabRootand lines 73-78 fromuseNativeTabNavigator.ts.
- Create a lightweight child component (e.g.
-
Result:
- When an RHP opens or closes, only
TabSwipeBackGestureControllerre-renders to togglegestureEnabled. useNativeTabNavigatorand<Tab.Navigator>remain completely untouched.- All 6 tab descriptors and screen components retain their cached identities, eliminating the re-render storm and making the "Create expense" modal open smoothly.
- When an RHP opens or closes, only
-
Prevent unnecessary tab-state re-renders:
- In
useNativeTabNavigator.ts:54, memoize thetabStateselector so that actions outside the tab navigator (like opening an RHP) do not trigger unnecessary reference changes if the underlying tab routes haven't changed.
- In
What automated tests can you add to prevent this from re-occurring?
Add a unit test in tests/unit/useNativeTabNavigatorTest.ts verifying that pushing an unrelated route to the root navigation state (e.g. pushing an RHP route) does not trigger a re-render or re-execution of useNativeTabNavigator or recreate screenOptions.
What alternative solutions did you explore? (Optional)
- Enabling
freezeOnBluron native tab screens: Rejected because freezing background tabs causes a blank/white frame flicker during native tab switches before React can unfreeze the target screen. - Applying
React.memoto each tab screen: Rejected becauseReact.memoviolates Expensify's React Compiler guidelines and does not prevent the top-level descriptor rebuild in<Tab.Navigator>. Decoupling the root navigation state listener is the architectural solution.
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~015c92a110b06ee5b3
Proposal
Please re-state the problem that we are trying to solve in this issue.
On mobile devices (iOS and Android), initiating the "Create expense" flow (or opening any Right-Hand Panel (RHP) modal) shows a severe latency regression (+33% slower, jumping from 264ms to 352ms on iOS, and from 524ms to 666ms on Android).
What is the root cause of that problem?
As profiled by Contributor+ reviewer @nyomanjyotisa on real iOS and Android devices, the regression is not caused by React component re-renders of the native tab bar or tab screens (the React profiler confirms screens do not re-render, and Android's tabBarHidden remains false throughout the transition; extracting root-focus subscriptions does not provide consistent speedups).
The actual performance bottleneck is situated at the React Native Fabric shadow-tree layout and Reanimated commit layer across permanently mounted background tabs:
-
All 6 tabs remain continuously mounted without freezing on native: With the introduction of the native tab bar (PR #101339),
lazy: truewas removed andFreezeWrapperon native (src/libs/Navigation/AppNavigator/FreezeWrapper/index.native.tsx) is a deliberate no-op (return children;) to prevent blank screen flashes when switching native tabs. Consequently, all tab screens (Inbox, Spend, Insights, Workspaces, Settings) remain mounted in the Fabric tree. -
The Spend tab runs an infinite
LoadingBaranimation loop in the background from app startup: Insrc/pages/Search/SearchPageNarrow/index.tsx(lines 271–285):const isDataLoaded = shouldUseLiveData || isSearchDataLoaded(searchResults, queryJSON); const shouldShowLoadingState = !isOffline && (!isDataLoaded || isSearchPending(searchResults));Because Spend mounts at startup in the background before the user has ever navigated to it,
useHasTabBeenShown(NAVIGATORS.SEARCH_FULLSCREEN_NAVIGATOR)inSearchPage.tsx:60correctly holds back search requests. However, because no search has run,isDataLoadedevaluates tofalse. As a result,shouldShowLoadingStateevaluates totrueon initial launch, mounting<LoadingBar shouldShow={true} />on the hidden Spend tab.LoadingBar.tsximmediately initiates an infinite looping animation viawithRepeat(..., -1)that runs indefinitely in the background. -
Background tabs animate loading bars during global in-flight requests: In
src/components/Navigation/TopBarWithLoadingBar.tsx(mounted inBaseSidebarScreen,WorkspaceListLayout, andInitialSettingsPage),shouldShowLoadingBarreadsuseLoadingBarVisibility(). When global background commands (OpenApp,ReconnectApp,OpenReport,ReadNewestAction) execute, multiple hidden tabs simultaneously runLoadingBaranimations. -
Layout property animations trigger continuous Yoga layout passes & Fabric shadow-tree commits: In
src/components/LoadingBar.tsx(lines 64–67), the indicator animates layout properties:const animatedIndicatorStyle = useAnimatedStyle(() => ({ left: `${left.get()}%`, width: `${width.get()}%`, }));In React Native Fabric, mutating layout properties (
left,width) on every frame forces Yoga layout recalculations and shadow-tree mutations. -
ReanimatedCommitHook.cppcontention during RHP navigation commits: When an RHP (such as "Create expense") opens, Fabric performs a navigation shadow-tree commit. Inside that commit, Reanimated's commit hook (ReanimatedCommitHook.cpp) re-evaluates all mounted animated views across the entire Fabric hierarchy. Having background tabs actively running layout property animations in an infinite loop forces Fabric and Reanimated to reconcile and re-layout these views during the navigation transaction, directly producing the +33% latency regression (+142ms on Android, +88ms on iOS).
What changes do you think we should make in order to solve the problem?
We solve this issue comprehensively across three targeted, non-breaking steps:
1. Prevent rogue background loading state on the Spend tab (SearchPageNarrow & SearchPage)
Pass hasSpendBeenShown from SearchPage.tsx into SearchPageNarrow.tsx (or query it directly) and gate shouldShowLoadingState. The Spend tab should only display a loading bar if the tab has actually been shown to the user:
In src/pages/Search/SearchPageNarrow/index.tsx:
--- a/src/pages/Search/SearchPageNarrow/index.tsx
+++ b/src/pages/Search/SearchPageNarrow/index.tsx
@@ -99,6 +99,7 @@ function SearchPageNarrow({
onSearchContentReady,
hasFilterBars,
isOverlayActive,
+ hasSpendBeenShown,
}: SearchPageNarrowProps) {
const shouldShowLoadingSkeleton = useSearchLoadingState(contentQueryJSON, contentSearchResults);
@@ -270,7 +271,7 @@ function SearchPageNarrow({
}
const isDataLoaded = shouldUseLiveData || isSearchDataLoaded(searchResults, queryJSON);
// Use the request state because `isLoading` also covers temporary UI loading that should not keep this bar visible.
- const shouldShowLoadingState = !isOffline && (!isDataLoaded || isSearchPending(searchResults));
+ const shouldShowLoadingState = !isOffline && hasSpendBeenShown && (!isDataLoaded || isSearchPending(searchResults));
const contentContainerStyle = !isMobileSelectionModeEnabled ? searchListContentContainerStyle : undefined;
In src/pages/Search/SearchPage.tsx:
--- a/src/pages/Search/SearchPage.tsx
+++ b/src/pages/Search/SearchPage.tsx
@@ -207,6 +207,7 @@ function SearchPage({route}: SearchPageProps) {
onSearchContentReady={onSearchContentReady}
hasFilterBars={hasFilterBars}
isOverlayActive={isOverlayActive}
+ hasSpendBeenShown={hasSpendBeenShown}
/>
) : (
<SearchPageWide
2. Convert LoadingBar.tsx to GPU/Compositor transforms (Zero Yoga Layout Passes)
Replace layout property animations (left and width) with compositor transforms (translateX and scaleX). Transforms bypass Yoga layout passes and Fabric shadow-tree mutations entirely, executing purely on the UI thread/compositor:
In src/components/LoadingBar.tsx:
--- a/src/components/LoadingBar.tsx
+++ b/src/components/LoadingBar.tsx
@@ -14,14 +14,14 @@ type LoadingBarProps = {
};
function LoadingBar({shouldShow}: LoadingBarProps) {
- const left = useSharedValue(0);
- const width = useSharedValue(0);
+ const translateX = useSharedValue(-100);
+ const scaleX = useSharedValue(0);
const opacity = useSharedValue(0);
const styles = useThemeStyles();
useEffect(() => {
if (shouldShow) {
- left.set(0);
- width.set(0);
+ translateX.set(-100);
+ scaleX.set(0);
opacity.set(withTiming(1, {duration: CONST.ANIMATED_PROGRESS_BAR_OPACITY_DURATION}));
- left.set(
+ translateX.set(
withDelay(
CONST.ANIMATED_PROGRESS_BAR_DELAY,
withRepeat(
withSequence(
withTiming(0, {duration: 0}),
- withTiming(0, {duration: CONST.ANIMATED_PROGRESS_BAR_DURATION, easing: Easing.bezier(0.65, 0, 0.35, 1)}),
- withTiming(100, {duration: CONST.ANIMATED_PROGRESS_BAR_DURATION, easing: Easing.bezier(0.65, 0, 0.35, 1)}),
+ withTiming(-30, {duration: CONST.ANIMATED_PROGRESS_BAR_DURATION, easing: Easing.bezier(0.65, 0, 0.35, 1)}),
+ withTiming(100, {duration: CONST.ANIMATED_PROGRESS_BAR_DURATION, easing: Easing.bezier(0.65, 0, 0.35, 1)}),
),
-1,
false,
),
),
);
- width.set(
+ scaleX.set(
withDelay(
CONST.ANIMATED_PROGRESS_BAR_DELAY,
withRepeat(
withSequence(
withTiming(0, {duration: 0}),
withTiming(1, {duration: CONST.ANIMATED_PROGRESS_BAR_DURATION, easing: Easing.bezier(0.65, 0, 0.35, 1)}),
withTiming(0, {duration: CONST.ANIMATED_PROGRESS_BAR_DURATION, easing: Easing.bezier(0.65, 0, 0.35, 1)}),
),
-1,
false,
),
),
);
} else {
opacity.set(
withTiming(0, {duration: CONST.ANIMATED_PROGRESS_BAR_OPACITY_DURATION}, () => {
- cancelAnimation(left);
- cancelAnimation(width);
+ cancelAnimation(translateX);
+ cancelAnimation(scaleX);
}),
);
}
// we want to update only when shouldShow changes
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [shouldShow]);
- const animatedIndicatorStyle = useAnimatedStyle(() => ({
- left: `${left.get()}%`,
- width: `${width.get()}%`,
- }));
+ const animatedIndicatorStyle = useAnimatedStyle(() => ({
+ transform: [
+ {translateX: `${translateX.get()}%` as unknown as number},
+ {scaleX: scaleX.get()},
+ ],
+ }));
3. Suppress loading bars in unfocused tab screens (TopBarWithLoadingBar.tsx)
Gate TopBarWithLoadingBar on whether the screen is currently focused using useIsScreenFocused(). Background tabs (Settings, Workspaces, Inbox) will not spin loading bar animations when in-flight requests occur in other parts of the app:
In src/components/Navigation/TopBarWithLoadingBar.tsx:
--- a/src/components/Navigation/TopBarWithLoadingBar.tsx
+++ b/src/components/Navigation/TopBarWithLoadingBar.tsx
@@ -1,4 +1,5 @@
import {useLoadingBarVisibility} from '@hooks/useInFlightRequests';
+import useIsScreenFocused from '@hooks/useIsScreenFocused';
import React from 'react';
@@ -13,7 +14,8 @@ type TopBarWithLoadingBarProps = Omit<TopBarProps, 'shouldShowLoadingBar'>;
* Use this in places where shouldShowLoadingBar is NOT passed explicitly by the parent.
*/
function TopBarWithLoadingBar({breadcrumbLabel, shouldDisplaySearch, shouldDisplayHelpButton, cancelSearch, children}: TopBarWithLoadingBarProps) {
- const shouldShowLoadingBar = useLoadingBarVisibility();
+ const isScreenFocused = useIsScreenFocused();
+ const shouldShowLoadingBar = useLoadingBarVisibility() && isScreenFocused;
return (
<TopBar
What alternative solutions did you explore? (Optional)
- Re-enabling
react-freezeon native: Investigated unfreezing tabs viaFreezeWrapper/index.native.tsx. This was intentionally disabled in PR #101339 because the native tab bar switches tabs before JavaScript can complete the unfreeze pass, causing noticeable blank-screen flashing. - Subscribing to navigation state or memoizing tab options: Proposed by several contributors, but thoroughly debunked by @nyomanjyotisa's on-device profiling: the tab screens/options do not re-render during RHP open, and removing the subscription does not produce a measurable speedup.
- Completely unmounting background tab contents until first view:
While unmounting children saves memory, native tab bar containers expect non-zero layout dimensions to prevent layout recalculations upon initial selection. Gating active animations (
LoadingBar) and deferred queries achieves the performance gain while keeping tab layout stability intact.
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
📣 @jashory! 📣 Hey, it seems we don’t have your contributor details yet! You'll only have to do this once, and this is how we'll hire you on Upwork. Please follow these steps:
- Make sure you've read and understood the contributing guidelines.
- Get the email address used to login to your Expensify account. If you don't already have an Expensify account, create one here. If you have multiple accounts (e.g. one for testing), please use your main account email.
- Get the link to your Upwork profile. It's necessary because we only pay via Upwork. You can access it by logging in, and then clicking on your name. It'll look like this. If you don't already have an account, sign up for one here.
- Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details.
Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>
@nyomanjyotisa Here is the updated root-cause analysis based on profiling the navigation transaction lifecycle and why Create expense regressed on iOS/Android:
What is the root cause of that problem?
-
Why
tabBarHiddenstayedfalseand tabs didn't re-render from tab options: When an RHP (like Create expense) opens, it is pushed onto the parent stack (RootStackNavigator), not insideTabNavigator. WithinTabNavigator, the active tab route remains at root level (isTabRouteAtRoot(activeTabRoute) === true). Therefore,shouldShowNativeTabBarremainstrueon Android, and the tab bar options/icons do not trigger the slowdown. -
The Real Culprit:
markFocusedTabRouteForRemountinGetStateForActionHandlers.ts: Insrc/libs/Navigation/AppNavigator/createRootStackNavigator/GetStateForActionHandlers.ts(lines 80-84):if (preMountedRouteKey && !getIsNarrowLayout()) { tabStateForReplace = withFocusedTabInHistory(updatedTabState); } else if (existingTabState) { tabStateForReplace = markFocusedTabRouteForRemount(updatedTabState, existingTabState); }On mobile/narrow layouts (
getIsNarrowLayout() === true), when opening an RHP over a tab, the state handler explicitly invokesmarkFocusedTabRouteForRemount, which strips the existing key viagetKeylessRoute(focusedRoute).In React Navigation's native tab view (patched in
@react-navigation+bottom-tabs+7.19.2+004+stable-native-tab-identity.patch), the native tab is keyed byroute.name, but its child content is keyed byroute.key:children: /*#__PURE__*/_jsx(Deferred, { lazy: lazy, visible: isFocused || isPreloaded, ... }, route.key)Because
getKeylessRouteforces React Navigation to generate a fresh route key during rehydration, the entire screen hierarchy inside the active tab's split navigator unmounts and remounts. -
Why Windows / Mac showed 0% regression while iOS/Android jumped +33%: On wide layouts (desktop/web),
!getIsNarrowLayout()branches intowithFocusedTabInHistory(updatedTabState)and completely bypassesmarkFocusedTabRouteForRemount. The focused tab retains its stable key, so zero unmounting happens. On iOS and Android narrow layouts, remounting the tab screen runs concurrently in the same React commit tick as mounting the RHP (IOURequestStartPage), creating severe thread contention during the telemetry window (startSpan(SPAN_OPEN_CREATE_EXPENSE)).
What changes do you think we should make in order to solve the problem?
Preserve the focused tab route's key when navigating to an RHP with the native tab bar on narrow layout, avoiding the unmount/remount cycle of the underlying tab tree when RHP mounts:
In GetStateForActionHandlers.ts, allow narrow layouts with native tabs to preserve the tab key using withFocusedTabInHistory, matching the wide layout behavior.
Tagging @nyomanjyotisa for review.
This is not open for proposals
@BartekObudzinski Whoops! This issue is 2 days overdue. Let's get this updated quick!
@BartekObudzinski Whoops! This issue is 2 days overdue. Let's get this updated quick!
@BartekObudzinski Uh oh! This issue is overdue by 2 days. Don't forget to update your issues!
Proposal
Please re-state the problem that we are trying to solve in this issue.
On native (iOS and Android), opening any Right Hand Panel (RHP) modal (such as Create Expense, Search, or Settings sub-pages) causes NativeTabNavigator to re-render and call navigation.setOptions on the root stack during the RHP open transition commit, adding unnecessary render work to every RHP opening.
What is the root cause of that problem?
In src/libs/Navigation/AppNavigator/Navigators/NativeTabNavigator/useNativeTabNavigator.ts:
shouldShowNativeTabBar(lines 54–56) depends only on the tab navigator's own internal route state (state.routes[state.index]).- However,
useNativeTabNavigatoralso computesisFocusedRouteTabRoot(line 49) by subscribing to the global root navigation state viauseFocusedRoute(). When an RHP is pushed onto the root stack besideNativeTabNavigator, the globally focused route changes from the tab root to the RHP screen, flippingisFocusedRouteTabRootfromtruetofalse. - This state change forces
NativeTabNavigatorto re-render right in the middle of the RHP navigation commit, and triggers theuseEffectat lines 73–78 to callnavigation.setOptionson the parent root stack even though the tab navigator's own active tab andshouldShowNativeTabBarhave not changed.
What changes do you think we should make in order to solve the problem?
- In
src/libs/Navigation/AppNavigator/Navigators/NativeTabNavigator/useNativeTabNavigator.ts(lines 49–78):- Derive tab root focus (
isFocusedRouteTabRoot/shouldShowNativeTabBar) strictly from the tab navigator's own local navigation state (useNavigationStatescoped toNativeTabNavigatorrather than the global root stack'suseFocusedRoute), or guard thenavigation.setOptionseffect at lines 73–78 with a ref tracking the previousshouldShowNativeTabBarboolean sonavigation.setOptionsis only invoked whenshouldShowNativeTabBaractually flips.
- Derive tab root focus (
- Remove the global root-stack subscription from
useNativeTabNavigatorso pushing or popping an RHP on the root stack does not trigger a re-render ofNativeTabNavigator. - Add a unit test in
tests/unit/useNativeTabNavigatorTest.tsverifying that opening an RHP route on the root stack does not re-runnavigation.setOptionsor re-renderNativeTabNavigator.
What alternative solutions did you explore? (Optional)
We considered wrapping individual tab screens in React.memo, but preventing useNativeTabNavigator from subscribing to root-stack RHP focus changes eliminates the parent re-render and the redundant navigation.setOptions call at the source.