React Native is a powerful framework developed by Facebook that allows you to develop both iOS and Android applications with a single codebase. In this article, we'll explore all aspects of mobile app development with React Native.
Introduction to React Native
Why React Native?
- iOS and Android support with a single codebase
Installation
npx react-native init MyApp
cd MyApp
npm start
Basic Components
View and Text
import { View, Text } from 'react-native';
function App() {
return (
<View>
<Text>Hello React Native!</Text>
</View>
);
}
StyleSheet
import { StyleSheet } from 'react-native';
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
},
title: {
fontSize: 24,
fontWeight: 'bold',
},
});
Navigation
React Navigation
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
const Stack = createStackNavigator();
function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Details" component={DetailsScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
State Management
React Context
import { createContext, useContext, useState } from 'react';
const AppContext = createContext();
function AppProvider({ children }) {
const [user, setUser] = useState(null);
return (
<AppContext.Provider value={{ user, setUser }}>
{children}
</AppContext.Provider>
);
}
function useApp() {
return useContext(AppContext);
}
API Integration
Fetch API
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
} catch (error) {
console.error('Error:', error);
}
}
Platform-Specific Code
Platform Detection
import { Platform } from 'react-native';
if (Platform.OS === 'ios') {
// iOS specific code
} else if (Platform.OS === 'android') {
// Android specific code
}
Performance Optimization
Memoization
import { useMemo } from 'react';
function ExpensiveComponent({ data }) {
const processedData = useMemo(() => {
return expensiveCalculation(data);
}, [data]);
return <View>{/ Render /}</View>;
}
Testing
Jest and React Native Testing Library
import { render, fireEvent } from '@testing-library/react-native';
import Button from './Button';
test('button press', () => {
const { getByText } = render(<Button />);
const button = getByText('Press me');
fireEvent.press(button);
// Assertions
});
Deployment
iOS Deployment
1. Open the project in Xcode
2. Configure Signing & Capabilities
3. Create Archive
4. Upload to App Store
Android Deployment
1. Create release build
2. Sign with signing key
3. Upload to Google Play Console
Conclusion
React Native is a powerful tool for cross-platform mobile app development. With what you've learned in this guide, you can start building native-performance mobile applications.