In this lesson, you will learn how to keep your app’s startup time snappy by ensuring the JavaScript bundle only includes the code your users actually need.
What is a Bundle?
When you build your Expo app, the entire codebase—every library, helper function, and component—is compressed into a single "bundle" file that the JavaScript engine reads. If this file is too large, the app takes longer to download and parse, leading to a sluggish startup. We use Tree-Shaking and Code Splitting to trim the fat.
Tree-Shaking
Tree-shaking is like pruning a dead branch off a tree. Most modern JavaScript bundlers (like Metro, which Expo uses) automatically remove "dead code"—functions or modules that you imported but never actually used in your application. To help the bundler do this effectively, prefer named imports over default imports:
// Good: The bundler can see you only need 'button'
import { button } from './components/library';
// Less ideal: The bundler might include the entire library
import library from './components/library';
By explicitly importing only what you need, you prevent the bundler from including unused features from large utility libraries like lodash or moment.
Code Splitting
In a standard setup, everything loads at once. Code splitting allows you to defer the loading of non-essential parts of your app until the user actually asks for them. In Expo, we often handle this by using dynamic import() statements for complex screens or heavy assets that aren't needed on the home screen.
Instead of importing a heavy chart library at the top of your file, you can load it inside a function triggered by a user action:
const loadHeavyFeature = async () => {
const { HeavyChart } = await import('./HeavyChartComponent');
// Now render the component...
};
By delaying the load of "heavy" components until the moment of interaction, the initial app launch remains fast and responsive.
Key Takeaway: Optimize your bundle by using named imports to enable tree-shaking and deferring the loading of non-essential components to keep your initial launch footprint small.