Code Splitting & Lazy Loading
Implement code splitting and lazy loading to improve app performance and reduce initial bundle size. This is a foundational concept in cross-platform mobile development that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world React Native experience. Take your time with each section and practice the examples
Code Splitting Strategies
Split your React Native app into smaller chunks and load them on-demand to improve startup time and reduce memory usage.. This is an essential concept that every React Native developer must understand thoroughly. In professional development environments, getting this right can mean the difference between code that works reliably and code that breaks in production. The following sections break this down into clear, digestible pieces with practical examples you can try immediately
Lazy Loading Components
Implement lazy loading for screens, components, and features to optimize app performance and user experience.. This is an essential concept that every React Native developer must understand thoroughly. In professional development environments, getting this right can mean the difference between code that works reliably and code that breaks in production. The following sections break this down into clear, digestible pieces with practical examples you can try immediately
Advanced Code Splitting Example
// utils/lazyLoader.js
import { lazy, Suspense } from 'react';
import { View, ActivityIndicator, Text } from 'react-native';
// Lazy load heavy components
const HeavyChart = lazy(() => import('./HeavyChart'));
const MapComponent = lazy(() => import('./MapComponent'));
const VideoPlayer = lazy(() => import('./VideoPlayer'));
// Loading component
const LoadingSpinner = ({ message = 'Loading...' }) => (
<View style={styles.loadingContainer}>
<ActivityIndicator size="large" color="#2196F3" />
<Text style={styles.loadingText}>{message}</Text>
</View>
);
// Lazy wrapper component
const LazyWrapper = ({ children, fallback = <LoadingSpinner /> }) => (
<Suspense fallback={fallback}>
{children}
</Suspense>
);
// Route-based code splitting
const routes = {
Home: lazy(() => import('./screens/HomeScreen')),
Profile: lazy(() => import('./screens/ProfileScreen')),
Settings: lazy(() => import('./screens/SettingsScreen')),
Charts: lazy(() => import('./screens/ChartsScreen')),
Maps: lazy(() => import('./screens/MapsScreen')),
};
// Dynamic route loader
const loadRoute = async (routeName) => {
try {
const route = routes[routeName];
if (route) {
return await route();
}
throw new Error(`Route ${routeName} not found`);
} catch (error) {
console.error('Error loading route:', error);
return null;
}
};
// Feature-based code splitting
const features = {
analytics: lazy(() => import('./features/analytics')),
notifications: lazy(() => import('./features/notifications')),
payments: lazy(() => import('./features/payments')),
social: lazy(() => import('./features/social')),
};
// Conditional feature loading
const loadFeature = async (featureName, condition) => {
if (condition) {
try {
const feature = features[featureName];
if (feature) {
return await feature();
}
} catch (error) {
console.error(`Error loading feature ${featureName}:`, error);
}
}
return null;
};
// Performance monitoring for lazy loading
const withPerformanceMonitoring = (Component, componentName) => {
return (props) => {
const startTime = Date.now();
React.useEffect(() => {
const loadTime = Date.now() - startTime;
console.log(`${componentName} loaded in ${loadTime}ms`);
// Send to analytics
analytics().logEvent('component_load_time', {
component: componentName,
loadTime,
});
}, []);
return <Component {...props} />;
};
};
const styles = {
loadingContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 20,
},
loadingText: {
marginTop: 10,
fontSize: 16,
color: '#666',
},
};
export { LazyWrapper, loadRoute, loadFeature, withPerformanceMonitoring };
// Usage example
const App = () => {
const [currentRoute, setCurrentRoute] = useState('Home');
return (
<LazyWrapper>
{React.createElement(routes[currentRoute])}
</LazyWrapper>
);
};