تحسين أداء React Native في 2024: دليل شامل
فريق Dev Ring
خبراء React Native في تونس
فريق Dev Ring
خبراء React Native في تونس
في 2024، يواصل React Native التطور بوتيرة سريعة. ومع وصولالمعمارية الجديدة التي تتضمن Fabric وTurboModules، تغيرت إمكانيات تحسين الأداء جذريًا.
في Dev Ring نرافق عملاءنا في تونس لتحسين تطبيقات React Native. إليك خلاصة خبرتنا حول أكثر التقنيات فاعلية في 2024.
تمثل Fabric أكبر ثورة في React Native منذ إطلاقه. تستبدل هذه المعمارية الجديدة الجسر غير المتزامن بين JavaScript والكود الأصلي بتواصلمتزامن ومكتوب Typing.
# مشروع جديد مع المعمارية الجديدة
npx react-native@latest init MyApp --template react-native-template-typescript
# ترحيل مشروع قائم
cd ios && RCT_NEW_ARCH_ENABLED=1 pod install
cd android && ./gradlew clean && ./gradlew assembleDebug -PnewArchEnabled=trueتتطلب Fabric إصدار React Native 0.68+. تأكد أن جميع الاعتمادات متوافقة مع المعمارية الجديدة.
تتيح TurboModules تحميلًا lazy ومحسنًا للوحدات الأصلية، مما يقلل بشكل كبير من زمن إقلاع التطبيق.
import type { TurboModule } from 'react-native';
import { TurboModuleRegistry } from 'react-native';
export interface Spec extends TurboModule {
getMemoryInfo(): Promise<{
totalMemory: number;
freeMemory: number;
usedMemory: number;
}>;
optimizeBundle(options: {
enableHermes: boolean;
minify: boolean;
}): Promise<boolean>;
}
export default TurboModuleRegistry.getEnforcing<Spec>('PerformanceModule');import { useEffect, useState } from 'react';
import PerformanceModule from '../specs/NativePerformanceModule';
export const usePerformanceMonitoring = () => {
const [memoryInfo, setMemoryInfo] = useState(null);
useEffect(() => {
const interval = setInterval(async () => {
try {
const info = await PerformanceModule.getMemoryInfo();
setMemoryInfo(info);
// تنبيه إذا تجاوز استخدام الذاكرة 80%
if (info.usedMemory / info.totalMemory > 0.8) {
console.warn('High memory usage detected');
}
} catch (error) {
console.error('Performance monitoring error:', error);
}
}, 5000);
return () => clearInterval(interval);
}, []);
return { memoryInfo };
};const { getDefaultConfig } = require('expo/metro-config');
const config = getDefaultConfig(__dirname);
// تحسينات الإنتاج
config.transformer.minifierConfig = {
keep_fnames: false,
mangle: {
keep_fnames: false,
},
output: {
comments: false,
},
};
// Tree Shaking مكثف
config.resolver.platforms = ['native', 'android', 'ios'];
config.resolver.assetExts.push('bin');
// تحسين الصور
config.transformer.assetPlugins = ['expo-asset/tools/hashAssetFiles'];
module.exports = config;import React, { Suspense, lazy } from 'react';
import { ActivityIndicator, View } from 'react-native';
const LazyScreen = lazy(() => import('../screens/HeavyScreen'));
export const OptimizedNavigator = () => (
<Suspense
fallback={
<View style={{ flex: 1, justifyContent: 'center'}>
<ActivityIndicator size="large" />
</View>
}
>
<LazyScreen />
</Suspense>
);
// Preload مشروط
export const preloadHeavyScreen = () => {
if (__DEV__) return;
import('../screens/HeavyScreen');
};يظل Flipper الأداة المفضلة لـ profiling، لكن مع إضافات محسنة لـ Fabric:
export class PerformanceProfiler {
private static instance: PerformanceProfiler;
private marks: Map<string, number> = new Map();
static getInstance(): PerformanceProfiler {
if (!this.instance) {
this.instance = new PerformanceProfiler();
}
return this.instance;
}
mark(name: string): void {
this.marks.set(name, Date.now());
}
measure(startMark: string, endMark: string): number {
const start = this.marks.get(startMark);
const end = this.marks.get(endMark);
if (!start || !end) {
throw new Error('Marks not found');
}
return end - start;
}
// تكامل مع Flipper
reportToFlipper(measurement: string, duration: number): void {
if (__DEV__) {
console.log('[Performance] ' + measurement + ': ' + duration + 'ms');
}
}
}import { create } from 'zustand';
import { subscribeWithSelector } from 'zustand/middleware';
interface AppState {
user: User | null;
posts: Post[];
loading: boolean;
}
export const useAppStore = create<AppState>()(
subscribeWithSelector((set, get) => ({
user: null,
posts: [],
loading: false,
// إجراءات محسّنة
setUser: (user: User) => set({ user }, false, 'setUser'),
// تحديث جزئي لتجنّب re-renders
updateUserProfile: (profile: Partial<User>) =>
set((state) => ({
user: state.user ? { ...state.user, ...profile } : null
}), false, 'updateUserProfile'),
}))
);
// Hook محسّن لتجنّب re-renders غير الضرورية
export const useUser = () => useAppStore((state) => state.user);import React, { memo } from 'react';
import { Image, ImageProps } from 'react-native';
interface OptimizedImageProps extends ImageProps {
priority?: 'high' | 'low';
placeholder?: boolean;
}
export const OptimizedImage = memo<OptimizedImageProps>(({
priority = 'low',
placeholder = true,
...props
}) => {
return (
<Image
{...props}
// Cache محسّن
cache="force-cache"
// Lazy loading للصور غير الحرجة
loadingIndicatorSource={
placeholder ? require('../assets/placeholder.png') : undefined
}
// Preload مشروط
onLoadStart={() => {
if (priority === 'high') {
// Preload للصور المرتبطة
}
}}
/>
);
});يتطلب تحسين أداء React Native في 2024 مقاربة شموليةتجمع بين المعماريات الجديدة وأفضل ممارسات التطوير والمراقبة المستمرة.
في Dev Ring نُتقن هذه التقنيات المتقدمة لتسليم تطبيقات موبايل عالية الأداء لعملائنا في تونس. تواصل معنا لتحسين مشاريع React Native الخاصة بك.
معمارية متزامنة جديدة
تحميل lazy محسّن
مراقبة فورية
يواصل React Native التطور بسرعة، ومعه تقنيات تحسين الأداء. في 2024، تتيح أساليب وأدوات جديدة تحسين أداء تطبيقات الموبايل بشكل ملحوظ.
تحسّن المعمارية الجديدة Fabric أداء الرندر بشكل كبير. كما تتيح TurboModules تواصلًا أكثر كفاءة بين JavaScript والكود الأصلي.
import { FlatList } from 'react-native';
<FlatList
data={items}
renderItem={renderItem}
keyExtractor={item => item.id}
getItemLayout={(data, index) => (
{ length: ITEM_HEIGHT, offset: ITEM_HEIGHT * index, index }
)}
removeClippedSubviews={true}
maxToRenderPerBatch={10}
windowSize={10}
initialNumToRender={5}
/>الصور غالبًا ما تكون عنق الزجاجة في تطبيقات React Native. إليك بعض التقنيات:
import FastImage from 'react-native-fast-image';
<FastImage
style={{ width: 200, height: 200 }}
source={{
uri: 'https://example.com/image.jpg',
priority: FastImage.priority.high,
}}
resizeMode={FastImage.resizeMode.contain}
/>import FastImage from 'react-native-fast-image';
<FastImage
style={{ width: 200, height: 200 }}
source={{
uri: 'https://unsplash.it/400/400?image=1',
priority: FastImage.priority.normal,
}}
/>استخدم react-native-reanimated للحصول على حركات سلسة تعمل على UI thread:
import Animated, {
useSharedValue,
useAnimatedStyle,
withTiming,
} from 'react-native-reanimated';
const AnimatedComponent = () => {
const opacity = useSharedValue(0);
const animatedStyles = useAnimatedStyle(() => {
return {
opacity: opacity.value,
};
});
const fadeIn = () => {
opacity.value = withTiming(1, { duration: 500 });
};
return (
<Animated.View style={animatedStyles}>
{/* محتوى */}
</Animated.View>
);
};قلّل حجم البداية لتطبيقك باستخدام code splitting:
// Lazy loading للمكوّنات
const LazyComponent = React.lazy(() => import('./LazyComponent'));
function App() {
return (
<Suspense fallback={<Loading />}>
<LazyComponent />
</Suspense>
);
}يتطلب تحسين أداء React Native مقاربة شمولية تجمع بين أفضل ممارسات التطوير، واستخدام الأدوات المناسبة، والمتابعة المستمرة لمقاييس الأداء.
في 2024، مع استقرار معمارية Fabric وأدوات profiling الجديدة، أصبح بناء تطبيقات React Native عالية الأداء أسهل من أي وقت مضى، لتنافس التطبيقات الأصلية.