React Native in 2024: Modern Mobile Development Guide
React Native in 2024: Modern Mobile Development Guide
React Native has matured significantly in 2024, introducing the New Architecture, better performance, and enhanced developer experience. Here's everything you need to know about building modern mobile apps.
Why React Native in 2024?
- Cross-platform efficiency: Write once, run on iOS and Android
- Native performance: New Architecture delivers 60+ FPS
- Rich ecosystem: Extensive libraries and community support
- Fast development: Hot reload and excellent debugging tools
1. Setting Up a Modern React Native Project
# Create new project with Expo (recommended)
npx create-expo-app@latest MyApp --template tabs
# Or with React Native CLI
npx react-native@latest init MyApp --version 0.74.0
# Navigate and start
cd MyApp
npm start
Project Structure Best Practices
src/
components/ # Reusable UI components
screens/ # Screen components
hooks/ # Custom hooks
utils/ # Helper functions
types/ # TypeScript types
services/ # API calls
stores/ # State management
2. New Architecture Benefits
The New Architecture (Fabric + TurboModules) is production-ready and offers:
- Better performance: Native-level rendering
- Improved memory usage: Efficient resource management
- Enhanced developer experience: Better debugging and profiler
// Optimized component with New Architecture
import React from 'react';
import { FlatList, Text, View, StyleSheet } from 'react-native';
const ProductList = ({ products }) => {
const renderProduct = ({ item }) => (
<View style={styles.productCard}>
<Text style={styles.title}>{item.name}</Text>
<Text style={styles.price}>${item.price}</Text>
</View>
);
return (
<FlatList
data={products}
renderItem={renderProduct}
keyExtractor={item => item.id}
// Performance optimizations
removeClippedSubviews={true}
maxToRenderPerBatch={10}
windowSize={5}
getItemLayout={(data, index) => ({
length: 100,
offset: 100 * index,
index,
})}
/>
);
};
3. Modern Navigation with Expo Router
Expo Router brings file-based routing similar to Next.js:
// app/_layout.tsx
import { Stack } from 'expo-router';
import { StatusBar } from 'expo-status-bar';
export default function RootLayout() {
return (
<>
<Stack>
<Stack.Screen name="(tabs)" options={{ headerShown: false }} />
<Stack.Screen name="modal" options={{ presentation: 'modal' }} />
</Stack>
<StatusBar style="auto" />
</>
);
}
// app/(tabs)/home.tsx
import { Text, View } from 'react-native';
export default function HomeScreen() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Welcome to Home!</Text>
</View>
);
}
4. State Management with Zustand
Zustand provides simple, performant state management:
// stores/useStore.js
import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import AsyncStorage from '@react-native-async-storage/async-storage';
export const useAppStore = create(
persist(
(set, get) => ({
user: null,
theme: 'light',
// Actions
setUser: (user) => set({ user }),
setTheme: (theme) => set({ theme }),
// Async actions
login: async (credentials) => {
try {
const response = await fetch('/api/login', {
method: 'POST',
body: JSON.stringify(credentials),
});
const user = await response.json();
set({ user });
} catch (error) {
console.error('Login failed:', error);
}
},
}),
{
name: 'app-storage',
storage: createJSONStorage(() => AsyncStorage),
}
)
);
5. Animations with Reanimated
Create smooth 60fps animations:
import Animated, {
useSharedValue,
useAnimatedStyle,
withSpring,
withTiming,
} from 'react-native-reanimated';
import { Pressable } from 'react-native';
function AnimatedButton({ children, onPress }) {
const scale = useSharedValue(1);
const opacity = useSharedValue(1);
const animatedStyle = useAnimatedStyle(() => ({
transform: [{ scale: scale.value }],
opacity: opacity.value,
}));
const handlePressIn = () => {
scale.value = withSpring(0.95);
opacity.value = withTiming(0.8);
};
const handlePressOut = () => {
scale.value = withSpring(1);
opacity.value = withTiming(1);
};
return (
<Pressable
onPressIn={handlePressIn}
onPressOut={handlePressOut}
onPress={onPress}
>
<Animated.View style={[styles.button, animatedStyle]}>
{children}
</Animated.View>
</Pressable>
);
}
6. Performance Optimization Tips
Image Optimization
import FastImage from 'react-native-fast-image';
function OptimizedImage({ source, style }) {
return (
<FastImage
style={style}
source={{
uri: source,
priority: FastImage.priority.normal,
cache: FastImage.cacheControl.immutable,
}}
resizeMode={FastImage.resizeMode.cover}
/>
);
}
List Performance
function PerformantList({ data }) {
const getItemLayout = (data, index) => ({
length: ITEM_HEIGHT,
offset: ITEM_HEIGHT * index,
index,
});
return (
<FlatList
data={data}
getItemLayout={getItemLayout}
removeClippedSubviews={true}
maxToRenderPerBatch={10}
windowSize={10}
initialNumToRender={10}
/>
);
}
7. Testing Strategies
Component Testing
// __tests__/Button.test.js
import React from 'react';
import { render, fireEvent } from '@testing-library/react-native';
import { Button } from '../components/Button';
describe('Button Component', () => {
it('calls onPress when pressed', () => {
const mockPress = jest.fn();
const { getByText } = render(
<Button onPress={mockPress}>Press me</Button>
);
fireEvent.press(getByText('Press me'));
expect(mockPress).toHaveBeenCalled();
});
});
8. Build and Deployment
EAS Build Configuration
{
"build": {
"development": {
"developmentClient": true,
"distribution": "internal"
},
"preview": {
"distribution": "internal"
},
"production": {}
}
}
Building for Production
# Build for App Store/Play Store
eas build --platform all --profile production
# Submit to stores
eas submit --platform all
9. Security Best Practices
// Secure storage
import * as SecureStore from 'expo-secure-store';
export const secureStorage = {
async setItem(key, value) {
await SecureStore.setItemAsync(key, value);
},
async getItem(key) {
return await SecureStore.getItemAsync(key);
},
async removeItem(key) {
await SecureStore.deleteItemAsync(key);
},
};
10. Debugging and Monitoring
// Performance monitoring
import { Performance } from 'react-native-performance';
// Crash reporting
import crashlytics from '@react-native-firebase/crashlytics';
export const monitor = {
startTrace: (name) => Performance.mark(`${name}-start`),
endTrace: (name) => Performance.mark(`${name}-end`),
logError: (error) => crashlytics().recordError(error),
};
Latest Libraries to Use in 2024
- Navigation: Expo Router or React Navigation 6
- State: Zustand or Redux Toolkit
- Animations: React Native Reanimated 3
- UI: NativeBase, React Native Elements, or Tamagui
- Forms: React Hook Form
- HTTP: TanStack Query (React Query)
- Storage: AsyncStorage + Zustand persist
Common Patterns and Solutions
Custom Hook for API Calls
import { useQuery } from '@tanstack/react-query';
function useUserProfile(userId) {
return useQuery({
queryKey: ['user', userId],
queryFn: () => fetch(`/api/users/${userId}`).then(res => res.json()),
staleTime: 5 * 60 * 1000, // 5 minutes
});
}
Theme Provider
import { createContext, useContext } from 'react';
const ThemeContext = createContext();
export function ThemeProvider({ children }) {
const theme = {
colors: {
primary: '#007AFF',
background: '#FFFFFF',
text: '#000000',
},
spacing: {
small: 8,
medium: 16,
large: 24,
},
};
return (
<ThemeContext.Provider value={theme}>
{children}
</ThemeContext.Provider>
);
}
export const useTheme = () => useContext(ThemeContext);
Conclusion
React Native in 2024 offers:
- Production-ready New Architecture for native performance
- File-based routing with Expo Router
- Modern state management solutions
- Smooth animations with Reanimated 3
- Excellent tooling and developer experience
- Strong ecosystem and community support
React Native continues to be the best choice for cross-platform mobile development, combining React's developer experience with native performance.
Getting Started Today
# Start your React Native journey
npx create-expo-app@latest MyAwesomeApp --template tabs
cd MyAwesomeApp
npm start
Happy coding! 🚀📱
About Ansh Gupta
Frontend Developer with 3 years of experience building modern web applications. Based in Indore, India, passionate about React, TypeScript, and creating exceptional user experiences.
Learn more about me