Skip to main content

Command Palette

Search for a command to run...

Shrinking Your React Native App – A Developer's Guide to Size Optimization

Updated
3 min read
Shrinking Your React Native App – A Developer's Guide to Size Optimization
P

My name is Priyanka Sharma, commonly referred to as lassiecoder within the tech community. With ~5 years of experience as a Software Developer, I specialize in mobile app development and web solutions. My technical expertise includes: – JavaScript, TypeScript, and React ecosystems (React Native, React.js, Next.js) – Backend technologies: Node.js, MongoDB – Cloud and deployment: AWS, Firebase, Fastlane – State management and data fetching: Redux, Rematch, React Query – Real-time communication: Websocket – UI development and testing: Storybook Currently, I'm contributing my skills to The Adecco Group, a leading Swiss company known for innovative solutions.

Hello, Tech Scoopers! 👋

Welcome to another edition of cutting-edge development insights. We're tackling a common obstacle for React Native developers: maximizing app size.

React Native apps can quickly balloon in size, leading to slower installations, higher storage requirements, and frustrated users. Here's how to trim down your app without sacrificing functionality.

Why Are React Native Apps Getting So Big?

Several factors contribute to bloated React Native applications:

  1. Oversized JavaScript Bundles: As your codebase grows, so does your JS bundle, especially when loaded with large third-party libraries and redundant code.

  2. Excessive Native Dependencies: While third-party native modules enhance functionality, they significantly increase binary size.

  3. Unoptimized Assets: High-resolution images, multiple font variations, and uncompressed videos can dramatically increase app size.

  4. Debug Configurations in Production: Debug builds include extra development tools and logs that shouldn't make it to release versions.

  5. Suboptimal Default Settings: React Native's default configurations often prioritize compatibility oversize efficiency.

Analyzing Your App's Size

Before optimizing, identify what's causing the bloat:

  • Use Android Studio APK Analyzer for Android apps or Xcode Archive Tool for iOS

  • Try react-native-bundle-visualizer to examine JavaScript bundle composition

  • Run this command to evaluate JS bundle size:

      react-native bundle --platform android --dev false --entry-file index.js --bundle-output ./bundle.js
    
  • Audit your codebase for unused resources and dependencies

Optimizing JavaScript Bundle Size

The JavaScript bundle is often the primary culprit in large app sizes:

  • Enable Minification: Ensure Metro Bundler is set to production mode to strip comments and whitespace

  • Activate Hermes Engine: This lightweight JavaScript engine compiles JS into compact bytecode.

    For Android, update android/app/build.gradle:

      project.ext.react = [
          enableHermes: true
      ]
    

    For iOS, enable via CocoaPods:

      use_react_native!(:path => config[:reactNativePath], :hermes_enabled => true)
    

    Then run:

      cd ios && pod install
    
  • Purge Unused Dependencies: Use npm prune to remove unnecessary packages

  • Implement Code Splitting: Use React.lazy() and Suspense to load components only when needed:

      const HeavyComponent = React.lazy(() => import('./HeavyComponent'));
    
      // In your render method
      <Suspense fallback={<Loading />}>
        <HeavyComponent />
      </Suspense>
    
  • Choose Lightweight Alternatives: Replace bulky libraries like Moment.js with leaner options like date-fns

Asset Optimization Techniques

Media files can quickly bloat your app:

  • Use Optimized Images: Implement better image loading with react-native-fast-image:

      import FastImage from 'react-native-fast-image';
    
      <FastImage
        source={{ uri: 'https://your-image-url.com' }}
        style={{ width: 100, height: 100 }}
        resizeMode={FastImage.resizeMode.contain}
      />
    
  • Load Assets Dynamically: Instead of bundling assets, load them from a CDN:

      <Image source={{ uri: 'https://cdn.example.com/image.jpg' }} style={{ width: 100, height: 100 }} />
    

Build Configuration Improvements

Fine-tune your build settings for significant size reductions:

  • Enable ProGuard/R8: Update android/app/build.gradle:

      android {
          buildTypes {
              release {
                  minifyEnabled true
                  proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
              }
          }
      }
    
  • Target Specific Architectures: Limit support in android/app/build.gradle:

      android {
          defaultConfig {
              ndk {
                  abiFilters "arm64-v8a", "armeabi-v7a"
              }
          }
      }
    
  • Optimize Localization: For iOS, update ios/Info.plist:

      <key>CFBundleLocalizations</key>
      <array>
          <string>en</string>
      </array>
    

    For Android, update android/app/build.gradle:

      android {
          defaultConfig {
              resConfigs "en"
          }
      }
    
  • Use App Bundles: Enable AAB in android/gradle.properties:

      android.bundle.enable=true
    

    Generate an AAB with:

      cd android && ./gradlew bundleRelease
    

Advanced Size-Reduction Strategies

For even more optimization:

  • Implement OTA Updates: Integrate CodePush:

      npm install react-native-code-push
    
  • Enable Multidex: For Android apps with numerous dependencies:

      android {
          defaultConfig {
              multiDexEnabled true
          }
      }
    
  • Utilize Dynamic Delivery: Configure Dynamic Features Modules:

      android {
          dynamicFeatures = [":feature_module"]
      }
    

By systematically addressing these areas, you can significantly reduce your React Native app's size, improving user experience and potentially increasing install conversion rates.

Remember that optimization is an ongoing process – regularly analyze your app to prevent size creep as new features are added.

Until next time,

lassiecoder


PS: If you found this newsletter helpful, don't forget to share it with your dev friends and hit that subscribe button!

If you found my work helpful, please consider supporting it through sponsorship.