Performance is critical for mobile app success. Users expect smooth 60fps animations and instant responses. This comprehensive guide covers React Native performance optimization from basics to advanced techniques.
Measuring Performance
Start with proper measurement tools:
typescript
import { Performance } from 'react-native';
// Measure component render time
const measure = (componentName: string) => (WrappedComponent: any) => {
return class extends React.Component {
componentWillMount() {
this.startTime = Performance.now();
}
componentDidMount() {
const duration = Performance.now() - this.startTime;
console.log(`${componentName} rendered in ${duration}ms`);
}
render() {
return <WrappedComponent {...this.props} />;
}
};
};Optimization Strategies
1. List Virtualization
typescript
import { FlatList } from 'react-native';
function OptimizedList({ data }) {
return (
<FlatList
data={data}
keyExtractor={(item) => item.id}
renderItem={({ item }) => <ListItem item={item} />}
initialNumToRender={10}
maxToRenderPerBatch={10}
windowSize={5}
removeClippedSubviews={true}
getItemLayout={(data, index) => ({
length: ITEM_HEIGHT,
offset: ITEM_HEIGHT * index,
index
})}
/>
);
}2. Memoization
typescript
import React, { memo, useMemo, useCallback } from 'react';
const ExpensiveComponent = memo(({ data, onUpdate }) => {
const processed = useMemo(() =>
expensiveOperation(data),
[data]
);
const handlePress = useCallback(() =>
onUpdate(processed),
[processed, onUpdate]
);
return <Button onPress={handlePress} />;
});3. Image Optimization
typescript
import { Image } from 'react-native';
const OptimizedImage = () => (
<Image
source={{ uri: 'https://example.com/image.jpg' }}
style={{ width: 100, height: 100 }}
resizeMode="cover"
defaultSource={require('./placeholder.png')}
fadeDuration={300}
/>
);Best Practices
- 1Avoid inline functions in render
- 2Use React.memo judiciously
- 3Optimize images and assets
- 4Minimize re-renders
- 5Use Hermes JavaScript engine
- 6Profile with React DevTools
Conclusion
React Native performance optimization requires understanding the bridge, measuring properly, and applying targeted optimizations. Focus on user-perceived performance first.