Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save SwarajDashDev/70182ed8371a58eaf93f0f85f6daf2ea to your computer and use it in GitHub Desktop.

Select an option

Save SwarajDashDev/70182ed8371a58eaf93f0f85f6daf2ea to your computer and use it in GitHub Desktop.
Reduce initial bundle size by lazily importing rarely used screens using React.lazy and Suspense in a React Native project.

Insight

When a mobile app ships with several feature‑rich screens, the initial JavaScript bundle can become bloated, leading to slower cold starts. While Metro’s inline requires help, a more granular approach is to lazily load the heavy screens only when the user navigates to them. React Native now supports React.lazy combined with Suspense (experimental) to split code at the component level, keeping the start‑up bundle lean.

Example

// src/navigation/AppNavigator.tsx
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { Suspense } from 'react';
import LoadingScreen from '../components/LoadingScreen';

const Stack = createStackNavigator();
const SettingsScreen = React.lazy(() => import('../screens/SettingsScreen'));

export default function AppNavigator() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Settings">
          {() => (
            <Suspense fallback={<LoadingScreen />}>
              <SettingsScreen />
            </Suspense>
          )}
        </Stack.Screen>
      </Stack.Navigator>
    </NavigationContainer>
  );
}

Takeaway

Wrap rarely visited screens in React.lazy + Suspense to defer their code until needed. Pair this with a lightweight fallback UI to keep the user experience smooth, and watch your app’s cold‑start time shrink dramatically.

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