Yo developers! π Siap-siap buat level up skill optimasi React Native kalian! Di artikel ini, kita bakal ngulik berbagai teknik optimasi yang bakal bikin app kalian ngebut maksimal. Dijamin auto smooth!
Daftar Isi π
- Optimasi Rendering
- Optimasi Memori
- Optimasi Jaringan
- Performa Native Modules
- Debugging dan Profiling
Optimasi Rendering π¨
1. Implementasi React.memo yang Tepat
// β Jangan gini
const UserCard = (props: UserProps) => (
{props.name}
{props.email}
);
// β
Yang bener gini
const UserCard = React.memo((props: UserProps) => (
{props.name}
{props.email}
), (prevProps, nextProps) => {
return prevProps.id === nextProps.id &&
prevProps.name === nextProps.name;
});
2. FlatList Optimization untuk Data Gede
const OptimizedList = () => {
const renderItem = useCallback(({ item }) => (
), []);
return (
item.id}
getItemLayout={(data, index) => ({
length: ITEM_HEIGHT,
offset: ITEM_HEIGHT * index,
index,
})}
removeClippedSubviews={true}
maxToRenderPerBatch={10}
windowSize={5}
initialNumToRender={5}
/>
);
};
Optimasi Memori πΎ
1. Mencegah Memory Leak
const ComponentWithCleanup = () => {
useEffect(() => {
const subscription = someAPI.subscribe();
// Jangan lupa cleanup! π§Ή
return () => {
subscription.unsubscribe();
};
}, []);
return
};
2. Image Caching yang Proper
import FastImage from 'react-native-fast-image';
const OptimizedImage = () => (
);
Optimasi Jaringan π
1. API Caching Implementation
import AsyncStorage from '@react-native-async-storage/async-storage';
const fetchWithCache = async (url: string) => {
const cacheKey = `api_cache_${url}`;
try {
// Check cache dulu
const cachedData = await AsyncStorage.getItem(cacheKey);
if (cachedData) {
return JSON.parse(cachedData);
}
// Kalo ga ada di cache, fetch dari API
const response = await fetch(url);
const data = await response.json();
// Simpan ke cache
await AsyncStorage.setItem(cacheKey, JSON.stringify(data));
return data;
} catch (error) {
console.error('Error fetching data:', error);
throw error;
}
};
2. Offline-First Strategy
import NetInfo from '@react-native-community/netinfo';
const OfflineFirstComponent = () => {
const [data, setData] = useState(null);
useEffect(() => {
const loadData = async () => {
// Check koneksi
const netInfo = await NetInfo.fetch();
if (netInfo.isConnected) {
// Online: fetch & cache
const newData = await fetchWithCache('/api/data');
setData(newData);
} else {
// Offline: load from cache
const cachedData = await AsyncStorage.getItem('offline_data');
setData(JSON.parse(cachedData));
}
};
loadData();
}, []);
return (
{/* Render your data */}
);
};
Performa Native Modules β‘
1. Efficient Bridging
// Native Module (Java/Kotlin)
@ReactMethod
public void processData(ReadableArray data, Promise promise) {
try {
// Process di background thread
new Thread(() -> {
// Heavy computation
WritableMap result = Arguments.createMap();
result.putString("status", "success");
promise.resolve(result);
}).start();
} catch (Exception e) {
promise.reject("ERROR", e.getMessage());
}
}
// JavaScript
const processDataJS = async (data: any[]) => {
try {
const result = await NativeModules.DataProcessor.processData(data);
return result;
} catch (error) {
console.error('Error processing data:', error);
throw error;
}
};
Debugging dan Profiling π
1. Performance Monitoring Setup
import Performance from 'react-native-performance';
const monitorComponentPerformance = (componentName: string) => {
Performance.mark(`${componentName}_start`);
return () => {
Performance.mark(`${componentName}_end`);
Performance.measure(
`${componentName}_measure`,
`${componentName}_start`,
`${componentName}_end`
);
};
};
// Usage in component
const MyComponent = () => {
useEffect(() => {
const stopMonitoring = monitorComponentPerformance('MyComponent');
return () => stopMonitoring();
}, []);
return ;
};
Tips Pro Buat Lo! π―
1. Bundle Size Diet
- Gunain ProGuard di Android
- Enable dead code elimination
- Split aplikasi pake dynamic imports
2. Memory Management
// Pake WeakMap buat data yang gede
const cache = new WeakMap();
const memoizedProcess = (obj) => {
if (cache.has(obj)) {
return cache.get(obj);
}
const result = heavyProcess(obj);
cache.set(obj, result);
return result;
};
3. Background Task Optimization
import BackgroundTask from 'react-native-background-task';
BackgroundTask.define(() => {
// Kerjain task yang ringan aja
BackgroundTask.finish();
});
Metrik yang Perlu Lo Pantau π
1. Time to Interactive (TTI)
- Target: < 3 detik
- Tools: React Native Performance Monitor
2. Memory Usage
- Target: < 100MB di foreground
- Tools: Android Studio Memory Profiler / Xcode Instruments
3. Frame Rate
- Target: 60 FPS
- Monitor pake: `global.performance`
Kesimpulan π
Nah, sekarang lo udah tau cara bikin app React Native yang optimal! Inget poin penting ini:
- Selalu implementasi proper memory management
- Optimize render cycle pake React.memo dan useCallback
- Implement proper caching strategy
- Monitor performance metrics regularly
Resources Keren π
Keep coding dan jangan lupa optimasi! π