Optimization Techniques

Back

Loading concept...

🚀 React Native Performance Optimization

The Backpack Analogy 🎒

Imagine you’re going on a hike. You have a backpack. If you pack too many heavy things, you’ll walk slowly and get tired fast. But if you pack smart—only what you need, in the right way—you’ll zoom up the mountain!

Your React Native app is like that backpack. We want it light, fast, and ready for adventure!


📦 Bundle Size Optimization

What is Bundle Size?

Think of your app like a lunchbox. Everything inside—your code, libraries, pictures—all gets packed together. This packed lunchbox is called the bundle.

The bigger the lunchbox, the longer it takes to carry!

When someone downloads your app, they download this bundle. A smaller bundle means:

  • ⚡ Faster downloads
  • 📱 Happy users
  • 💾 Less storage used

How to Make Your Bundle Smaller

1. Remove Unused Code (Tree Shaking)

Imagine you packed 10 toys but only play with 3. The other 7 are just taking space!

Tree shaking removes code you’re not using.

// ❌ BAD: Imports EVERYTHING
import lodash from 'lodash';
const result = lodash.get(obj, 'path');

// ✅ GOOD: Imports only what you need
import get from 'lodash/get';
const result = get(obj, 'path');

2. Use Smaller Libraries

Some toys are big, some are small. Choose the small ones!

// ❌ moment.js is HUGE (300KB+)
import moment from 'moment';

// ✅ date-fns is tiny (choose only functions)
import { format } from 'date-fns';

3. Code Splitting (Lazy Loading)

Don’t carry ALL your toys at once. Bring them when you need them!

// ❌ Loads everything at start
import HeavyComponent from './HeavyComponent';

// ✅ Loads only when needed
const HeavyComponent = React.lazy(
  () => import('./HeavyComponent')
);

4. Analyze Your Bundle

Use tools to see what’s making your backpack heavy:

npx react-native-bundle-visualizer

This shows you a colorful map of everything inside your bundle!

graph TD A["Your App Bundle"] --> B["Your Code"] A --> C["Libraries"] A --> D["Assets"] C --> E["Big Library 😰"] C --> F["Small Library 😊"] C --> G["Unused Code 🗑️"]

🖼️ Image Optimization

Why Images Matter

Pictures are like rocks in your backpack. They’re often the HEAVIEST things!

One big picture can be bigger than ALL your code combined. Yikes!

How to Make Images Light

1. Use the Right Size

Don’t pack a poster when you need a postcard!

// ❌ BAD: 4000x3000 image shown in tiny box
<Image
  source={require('./huge-photo.png')}
  style={{ width: 100, height: 100 }}
/>

// ✅ GOOD: Image matches display size
<Image
  source={require('./small-photo.png')}
  style={{ width: 100, height: 100 }}
/>

Rule: Make images 2x the display size (for crisp screens), no more!

2. Use the Right Format

Different picture types for different jobs:

Format Best For Size
WebP Photos & graphics Smallest!
PNG Logos, icons Medium
JPEG Photos only Small
SVG Simple icons Tiny!
// ✅ WebP for photos
<Image source={require('./photo.webp')} />

// ✅ SVG for icons
import HomeIcon from './home.svg';

3. Cache Your Images

Don’t download the same picture twice! Remember it!

// Using react-native-fast-image
import FastImage from 'react-native-fast-image';

<FastImage
  source={{
    uri: 'https://example.com/photo.jpg',
    priority: FastImage.priority.normal,
    cache: FastImage.cacheControl.immutable,
  }}
/>

4. Load Images Progressively

Show a blurry preview first, then the sharp version. Like magic!

<Image
  source={{ uri: imageUrl }}
  progressiveRenderingEnabled={true}
  fadeDuration={300}
/>
graph TD A["User Opens Screen"] --> B["Show Placeholder"] B --> C["Load Thumbnail"] C --> D["Load Full Image"] D --> E["Sharp &amp; Beautiful!"]

📋 List Optimization

The Problem with Lists

Imagine showing 1000 photos in a photo album. If you hold ALL 1000 at once, your arms get tired!

Lists in apps work the same way. Loading too many items = slow app.

The Solution: FlatList Magic

FlatList is like a smart helper. It only shows what you can see, and hides the rest!

// ❌ BAD: Renders ALL 1000 items
<ScrollView>
  {items.map(item => (
    <ItemComponent key={item.id} data={item} />
  ))}
</ScrollView>

// ✅ GOOD: Renders only visible items
<FlatList
  data={items}
  renderItem={({ item }) => (
    <ItemComponent data={item} />
  )}
  keyExtractor={item => item.id}
/>

Make FlatList Even Faster

1. Use getItemLayout for Same-Size Items

If all items are the same height, tell FlatList! It skips measuring.

<FlatList
  data={items}
  renderItem={renderItem}
  getItemLayout={(data, index) => ({
    length: 80,    // item height
    offset: 80 * index,
    index,
  })}
/>

2. Optimize with windowSize

Control how many screens worth of items to keep ready:

<FlatList
  data={items}
  renderItem={renderItem}
  windowSize={5}  // 5 screens worth
  initialNumToRender={10}
  maxToRenderPerBatch={5}
/>

3. Memoize Your Items

Don’t re-draw items that haven’t changed!

// Wrap your item component with memo
const ItemComponent = React.memo(({ data }) => {
  return (
    <View style={styles.item}>
      <Text>{data.title}</Text>
    </View>
  );
});

4. Use removeClippedSubviews

Items off-screen? Remove them completely!

<FlatList
  data={items}
  renderItem={renderItem}
  removeClippedSubviews={true}
/>

FlatList Cheat Config

Here’s a super-powered FlatList:

<FlatList
  data={items}
  renderItem={renderItem}
  keyExtractor={item => item.id}
  // Performance boosters
  initialNumToRender={10}
  maxToRenderPerBatch={5}
  windowSize={5}
  removeClippedSubviews={true}
  // If items are same height
  getItemLayout={(data, index) => ({
    length: ITEM_HEIGHT,
    offset: ITEM_HEIGHT * index,
    index,
  })}
/>
graph TD A["1000 Items"] --> B["FlatList"] B --> C["Shows ~10 items"] B --> D["Keeps ~50 ready"] B --> E["Ignores other 940!"] C --> F["Super Fast! ⚡"]

🎯 Quick Summary

Problem Solution
Big app download Remove unused code, use smaller libraries
Slow images Use WebP, right size, cache them
Laggy lists Use FlatList with optimizations

💪 You’ve Got This!

Remember our backpack? Now you know how to:

  1. Pack light (bundle optimization)
  2. Shrink your photos (image optimization)
  3. Only carry what you need (list optimization)

Your app will run like a champion sprinter! 🏃‍♂️💨

Happy coding! 🎉

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.