React Native
Updated: September 10, 2025Categories: Languages, Mobile
Printed from:
React Native Cheatsheet š
1. Installation and Setup
CLI Installation
Bash
123456789# Install React Native CLI globally
npm install -g react-native-cli
# Create a new project
npx react-native init MyProject
# Or using Expo CLI
npx create-expo-app MyProject
Environment Setup
-
iOS:
- Xcode (latest version)
- CocoaPods
- Homebrew
-
Android:
- Android Studio
- Android SDK
- Java Development Kit (JDK)
Environment Variables
Bash
1234567# Add to ~/.bash_profile or ~/.zshrc
export ANDROID_HOME=$HOME/Library/Android/sdk
export PATH=$PATH:$ANDROID_HOME/emulators
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/tools/bin
export PATH=$PATH:$ANDROID_HOME/platform-tools
2. Project Structure and Configuration
my-react-native-app/
ā
āāā android/ # Android native project
āāā ios/ # iOS native project
āāā src/
ā āāā components/ # Reusable components
ā āāā screens/ # Screen components
ā āāā navigation/ # Navigation configuration
ā āāā services/ # API, network calls
ā āāā utils/ # Utility functions
ā āāā context/ # Global state management
ā
āāā App.js # Main application component
āāā babel.config.js # Babel configuration
āāā metro.config.js # Metro bundler config
āāā package.json # Project dependencies
3. Core Components
Basic Components
jsx
1234567891011import { View, Text, Image, ScrollView } from 'react-native';
// View: Container component (like div)
<View style={styles.container}>
<Text>Hello React Native!</Text>
</View>
// ScrollView: Scrollable container
<ScrollView>
{items.map(item => <ItemComponent key={item.id} />)}
</ScrollView>
// FlatList: Efficient list rendering
<FlatList
data={items}
renderItem={({item}) => <ItemComponent item={item} />}
keyExtractor={item => item.id}
/>
4. Styling
StyleSheet
jsx
1234567891011121314151617import { StyleSheet, Platform } from 'react-native';
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: Platform.OS === 'ios' ? 'white' : 'blue'
},
text: {
fontSize: 16,
fontWeight: 'bold',
color: 'black'
}
});
Flexbox Layout
jsx
123456789const styles = StyleSheet.create({
container: {
flex: 1, // Take full available space
flexDirection: 'column', // Main axis vertical
justifyContent: 'center', // Center vertically
alignItems: 'center' // Center horizontally
}
});
5. Navigation (React Navigation)
jsx
12345678910111213import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
const Stack = createStackNavigator();
const Tab = createBottomTabNavigator();
function AppNavigator() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Details" component={DetailsScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
6. State Management
Local State
jsx
12345678910import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<View>
<Text>Count: {count}</Text>
<Button
title="Increment"
onPress={() => setCount(count + 1)}
/>
</View>
);
}
Context API
jsx
12345678910const ThemeContext = React.createContext();
function ThemeProvider({ children }) {
const [isDarkMode, setIsDarkMode] = useState(false);
return (
<ThemeContext.Provider value={{ isDarkMode, setIsDarkMode }}>
{children}
</ThemeContext.Provider>
);
}
7. Platform-Specific Code
jsx
1234567891011121314151617import { Platform, StatusBar } from 'react-native';
// Conditional rendering
const styles = {
container: Platform.select({
ios: { paddingTop: 30 },
android: { paddingTop: StatusBar.currentHeight }
})
};
// Platform-specific code
if (Platform.OS === 'ios') {
// iOS-specific implementation
} else if (Platform.OS === 'android') {
// Android-specific implementation
}
8. Native Modules and APIs
Camera
jsx
123456789import { launchCamera, launchImageLibrary } from 'react-native-image-picker';
const openCamera = () => {
launchCamera({ mediaType: 'photo' }, (response) => {
if (response.didCancel) return;
// Handle selected image
});
};
9. Networking
jsx
123456789101112131415161718192021const fetchData = async () => {
try {
const response = await fetch('https://api.example.com/data');
const json = await response.json();
setData(json);
} catch (error) {
console.error(error);
}
};
// Using Axios
import axios from 'axios';
const fetchWithAxios = async () => {
try {
const { data } = await axios.get('https://api.example.com/data');
setData(data);
} catch (error) {
console.error(error);
}
};
10. Storage
AsyncStorage
jsx
123456789101112131415161718192021import AsyncStorage from '@react-native-async-storage/async-storage';
// Store data
const storeData = async (key, value) => {
try {
await AsyncStorage.setItem(key, JSON.stringify(value));
} catch (error) {
console.error(error);
}
};
// Retrieve data
const getData = async (key) => {
try {
const value = await AsyncStorage.getItem(key);
return value != null ? JSON.parse(value) : null;
} catch (error) {
console.error(error);
}
};
11. Animations
jsx
123456789101112131415161718import { Animated, Easing } from 'react-native';
function AnimatedComponent() {
const fadeAnim = useRef(new Animated.Value(0)).current;
useEffect(() => {
Animated.timing(fadeAnim, {
toValue: 1,
duration: 1000,
useNativeDriver: true
}).start();
}, []);
return (
<Animated.View style={{ opacity: fadeAnim }}>
<Text>Fading View</Text>
</Animated.View>
);
}
12. Gestures
jsx
1234567891011121314import { PanGestureHandler, State } from 'react-native-gesture-handler';
function GestureComponent() {
const dragHandler = (event) => {
if (event.nativeEvent.state === State.ACTIVE) {
// Handle drag gesture
}
};
return (
<PanGestureHandler onGestureEvent={dragHandler}>
<View>...</View>
</PanGestureHandler>
);
}
13. Performance Optimization
- Use
FlatListinstead ofScrollViewfor long lists - Implement
shouldComponentUpdateor useReact.memo() - Use
useCallbackanduseMemo - Lazy load images
- Minimize bridge communication
14. Debugging
- Use React Native Debugger
- Enable remote debugging in dev menu
- Use
console.log()strategically - Utilize Flipper for advanced debugging
15. Testing
Bash
123456# Install testing libraries
npm install --save-dev jest @testing-library/react-native detox
# Run tests
npm test
16. Build and Deployment
Android
Bash
1234# Generate signed APK
cd android
./gradlew bundleRelease
iOS
Bash
123# Build for App Store
xcodebuild -workspace MyApp.xcworkspace -scheme MyApp archive
17. Push Notifications
jsx
1234567891011import messaging from '@react-native-firebase/messaging';
async function requestUserPermission() {
const authStatus = await messaging().requestPermission();
const enabled = /* check permission status */;
}
messaging().onMessage(async remoteMessage => {
// Handle foreground messages
});
18. Permissions
jsx
1234567891011121314151617import { PermissionsAndroid, Platform } from 'react-native';
const requestCameraPermission = async () => {
if (Platform.OS === 'android') {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.CAMERA
);
return granted === PermissionsAndroid.RESULTS.GRANTED;
} catch (err) {
console.warn(err);
return false;
}
}
return true;
};
19. Common Third-Party Libraries
- Navigation:
react-navigation - State Management:
redux,mobx - Forms:
formik,react-hook-form - HTTP Requests:
axios - Animations:
react-native-reanimated - Icons:
react-native-vector-icons
20. Troubleshooting Common Issues
- Metro bundler cache issues
- Pod install problems
- Version compatibility
- Native module linking
21. Best Practices
- Keep components small and focused
- Use TypeScript for type safety
- Consistent code formatting
- Handle errors gracefully
- Optimize performance
- Use environment configurations
- Follow platform-specific guidelines
Pro Tips:
- Always test on real devices
- Consider user experience
- Keep app size small
- Stay updated with React Native releases
Continue Learning
Discover more cheatsheets to boost your productivity