📱 React Native Cheat Sheet

Core components, StyleSheet, navigation, storage, APIs and animation.

🔍
🧩 Core Components
Essential imports
import {
  View, Text, Image, TextInput, ScrollView,
  TouchableOpacity, Pressable, Button,
  StyleSheet, Platform, Dimensions,
  ActivityIndicator, Modal, Alert,
} from 'react-native';
Basic structure
const App = () => (
  <View style={styles.container}>
    <Text style={styles.title}>Hello RN!</Text>
    <Image
      source={{ uri: 'https://example.com/img.png' }}
      source={require('./assets/logo.png')}
      style={{ width: 100, height: 100 }}
      resizeMode="contain"
    />
  </View>
);
TextInput
const [text, setText] = useState('');

<TextInput
  style={styles.input}
  value={text}
  onChangeText={setText}
  placeholder="Enter text"
  placeholderTextColor="#888"
  keyboardType="email-address"
  secureTextEntry        // for passwords
  autoCapitalize="none"
  returnKeyType="done"
  onSubmitEditing={() => submit()}
  multiline              // textarea mode
/>
Alert & Modal
Alert.alert("Title", "Message", [
  { text: "Cancel", style: "cancel" },
  { text: "OK", onPress: () => confirm() },
]);

<Modal visible={show} transparent animationType="slide">
  <View style={styles.overlay}>
    <View style={styles.sheet}>
      <Text>Sheet content</Text>
    </View>
  </View>
</Modal>
🎨 StyleSheet
StyleSheet.create
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#0c0c0e',
    padding: 16,
  },
  title: {
    fontSize: 24,
    fontWeight: '800',
    color: '#fff',
    textAlign: 'center',
  },
  shadow: {
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.25,
    shadowRadius: 4,
    elevation: 5,   // Android
  },
});
Dynamic & composed styles
// Array composition
<View style={[styles.base, isActive && styles.active]} />

// Inline dynamic
<View style={{ width: size, height: size, opacity: active ? 1 : 0.5 }} />

// Platform-specific
const s = StyleSheet.create({
  box: {
    ...Platform.select({
      ios:     { shadowColor: '#000', shadowRadius: 4 },
      android: { elevation: 4 },
    }),
  },
});
📐 Flexbox Layout
Flex direction & alignment
// Default: flexDirection: 'column' (unlike web)
flexDirection: 'row' | 'column' | 'row-reverse' | 'column-reverse'
justifyContent: 'flex-start' | 'center' | 'flex-end' | 'space-between' | 'space-around'
alignItems:     'flex-start' | 'center' | 'flex-end' | 'stretch' | 'baseline'
alignSelf:      'auto' | 'flex-start' | 'center' | 'flex-end' | 'stretch'

flex: 1            // take all remaining space
flexWrap: 'wrap'   // wrap to next line
Dimensions & safe area
import { Dimensions, useWindowDimensions } from 'react-native';

const { width, height } = Dimensions.get('window');

// Responsive hook
const { width, height } = useWindowDimensions();

// Safe area (react-native-safe-area-context)
import { useSafeAreaInsets } from 'react-native-safe-area-context';
const insets = useSafeAreaInsets();
<View style={{ paddingTop: insets.top }} />
📋 Lists
FlatList
<FlatList
  data={items}
  keyExtractor={item => item.id.toString()}
  renderItem={({ item, index }) => (
    <ItemRow item={item} />
  )}
  ItemSeparatorComponent={() => <View style={styles.divider} />}
  ListEmptyComponent={<Text>No items</Text>}
  ListHeaderComponent={<Header />}
  onEndReached={loadMore}
  onEndReachedThreshold={0.5}
  refreshing={loading}
  onRefresh={refresh}
  horizontal          // horizontal list
  numColumns={2}      // grid
/>
SectionList
const sections = [
  { title: "A", data: ["Apple", "Avocado"] },
  { title: "B", data: ["Banana", "Berry"] },
];

<SectionList
  sections={sections}
  keyExtractor={(item, i) => item + i}
  renderItem={({ item }) => <Text>{item}</Text>}
  renderSectionHeader={({ section }) => (
    <Text style={styles.header}>{section.title}</Text>
  )}
/>
👆 Touch & Gestures
Pressable (recommended)
<Pressable
  onPress={() => navigate()}
  onLongPress={() => showMenu()}
  style={({ pressed }) => [
    styles.btn,
    pressed && { opacity: 0.7, transform: [{ scale: 0.97 }] },
  ]}
  android_ripple={{ color: '#fff', borderless: false }}
  hitSlop={8}   // expand tap area
>
  <Text>Press me</Text>
</Pressable>
TouchableOpacity
<TouchableOpacity
  onPress={handlePress}
  activeOpacity={0.7}
  disabled={loading}
>
  <Text>Tap</Text>
</TouchableOpacity>
💾 Storage & State
AsyncStorage
import AsyncStorage from '@react-native-async-storage/async-storage';

// Save
await AsyncStorage.setItem('user', JSON.stringify(user));

// Load
const raw  = await AsyncStorage.getItem('user');
const user = raw ? JSON.parse(raw) : null;

// Remove
await AsyncStorage.removeItem('user');
await AsyncStorage.multiRemove(['a', 'b']);
Zustand (state management)
import { create } from 'zustand';

interface AuthStore {
  user: User | null;
  login:  (u: User) => void;
  logout: () => void;
}

const useAuth = create<AuthStore>(set => ({
  user: null,
  login:  user => set({ user }),
  logout: ()   => set({ user: null }),
}));

// Component
const { user, login, logout } = useAuth();
🌐 Network
fetch & axios
// fetch
const res  = await fetch('https://api.example.com/data');
const data = await res.json();

// axios
import axios from 'axios';
const { data } = await axios.get('/users');
await axios.post('/users', { name: 'Feem' });

// Interceptor
axios.interceptors.request.use(config => {
  config.headers.Authorization = `Bearer ${token}`;
  return config;
});
React Query (TanStack)
import { useQuery, useMutation } from '@tanstack/react-query';

const { data, isLoading, error } = useQuery({
  queryKey: ['users', userId],
  queryFn:  () => fetchUser(userId),
  staleTime: 1000 * 60,
});

const { mutate } = useMutation({
  mutationFn: (user) => createUser(user),
  onSuccess:  () => queryClient.invalidateQueries({ queryKey: ['users'] }),
});
📲 Platform APIs
Platform detection
Platform.OS          // 'ios' | 'android' | 'web'
Platform.Version     // iOS number | Android API level
Platform.isPad       // iOS only
Platform.isTV

Platform.select({
  ios:     { color: 'blue' },
  android: { color: 'green' },
  default: { color: 'gray' },
});
Common APIs
import { Linking, Vibration, Keyboard, BackHandler } from 'react-native';

Linking.openURL('https://example.com');
Linking.openURL('tel:+1234567890');

Vibration.vibrate(400);   // 400ms
Keyboard.dismiss();

// Android back button
useEffect(() => {
  const sub = BackHandler.addEventListener('hardwareBackPress', () => {
    navigation.goBack(); return true;
  });
  return () => sub.remove();
}, []);
✨ Animation
Animated API
const opacity = useRef(new Animated.Value(0)).current;

// Fade in
Animated.timing(opacity, {
  toValue: 1, duration: 300,
  useNativeDriver: true,
}).start();

// Spring
Animated.spring(scale, {
  toValue: 1, friction: 6,
  useNativeDriver: true,
}).start();

<Animated.View style={{ opacity }}>
  <Text>Fades in</Text>
</Animated.View>
Reanimated 2 (recommended)
import Animated, {
  useSharedValue, useAnimatedStyle,
  withSpring, withTiming, withSequence,
} from 'react-native-reanimated';

const offset = useSharedValue(0);

const animStyle = useAnimatedStyle(() => ({
  transform: [{ translateY: offset.value }],
}));

// Trigger
offset.value = withSpring(100);
offset.value = withTiming(0, { duration: 300 });

<Animated.View style={[styles.box, animStyle]} />