Skip to content
Tutorials Center
My learning

Topics

Lesson 71 of 71 ยท Practice and Review

React Native Cheat Sheet

A compact React Native cheat sheet: core components, style props, Flexbox values, FlatList props, navigation calls, hooks, storage and the Expo and EAS commands.

This is the page to keep open in a tab. It does not replace the lessons; each section links to the lesson that explains the idea in full. Think of it as a map: you will already know most of it, and when you do not, you will know where to read.

Read-only and stand-in. React Native code needs a native runtime, so the snippets here are plain code blocks. The two live examples are stand-ins that run in your browser: one draws the Flexbox values listed below with HTML boxes, the other shows how style arrays and Platform.select resolve. They model the behavior; they are not React Native.

The five-minute mental model

Native views View, Text, Image become real widgets.
Flexbox Column by default, no cascade.
Pressable Touch with pressed state.
FlatList Virtualized lists.

Everything else builds on these four.

1 / 2

Core components

Component Use it for Notes
View Container, like a div Flexbox, column by default
Text All text Strings outside Text crash
Image Pictures Remote images need width and height
ScrollView Short scrolling content Renders all children at once
FlatList Long lists Virtualized
SectionList Grouped lists Sticky headers
TextInput Typing Controlled with value and onChangeText
Pressable Anything touchable Style function gets { pressed }
Button Simple platform button Little styling control
Modal Full-screen overlay Controlled with visible
ActivityIndicator Spinner size, color
KeyboardAvoidingView Keep inputs above the keyboard behavior="padding" on iOS
SafeAreaView Avoid notches Prefer react-native-safe-area-context

See Core Components, Text and TextInput and Modals and Alerts.

TSX
import { Image, Pressable, ScrollView, StyleSheet, Text, TextInput, View } from 'react-native';

export function Card() {
  return (
    <View style={styles.card}>
      <Image source={{ uri: 'https://example.com/a.png' }} style={{ width: 64, height: 64 }} />
      <Text numberOfLines={2}>A long title that is cut after two lines</Text>
      <Pressable onPress={() => {}} style={({ pressed }) => [styles.btn, pressed && { opacity: 0.7 }]}>
        <Text>Open</Text>
      </Pressable>
    </View>
  );
}

const styles = StyleSheet.create({
  card: { padding: 16, gap: 8, borderRadius: 12, backgroundColor: 'white' },
  btn: { padding: 12, borderRadius: 8, backgroundColor: '#e2e8f0' },
});

Style props you use every day

Group Props
Size width, height, minWidth, maxHeight, aspectRatio (numbers are points, '50%' works)
Spacing margin*, padding* (Horizontal, Vertical, Top, ...), gap, rowGap, columnGap
Position position (relative or absolute), top, right, bottom, left, zIndex
Box backgroundColor, borderWidth, borderColor, borderRadius, overflow, opacity
Text color, fontSize, fontWeight (as a string, '600'), fontFamily, lineHeight, textAlign, letterSpacing, textDecorationLine
Shadow iOS: shadowColor, shadowOffset, shadowOpacity, shadowRadius. Android: elevation. Newer versions: boxShadow
Transform transform: [{ translateX: 10 }, { rotate: '45deg' }, { scale: 1.1 }]

There is no cascade and no CSS units. Style arrays merge left to right ([a, b, cond && c], falsy entries ignored). See Styling with StyleSheet and Sizing and Positioning.

Flexbox values

Prop Values Default
flexDirection column, row, column-reverse, row-reverse column
justifyContent (main axis) flex-start, center, flex-end, space-between, space-around, space-evenly flex-start
alignItems (cross axis) stretch, flex-start, center, flex-end, baseline stretch
alignSelf auto or the same as alignItems auto
flexWrap nowrap, wrap, wrap-reverse nowrap
flex number: 1 means grow and shrink with a zero basis none
flexGrow, flexShrink, flexBasis number, number, size 0, 0, auto

Two reminders: flex: 1 on the root of a screen makes it fill the window, and justifyContent and alignItems swap meaning when you change flexDirection. See Flexbox in React Native.

Pick values below and watch the boxes move. The stand-in uses HTML flexbox with React Native's defaults, so what you see matches the table.

Flexbox values at a glance

FlatList props

Prop Purpose
data, renderItem Required: the array and the row drawer
keyExtractor Stable string key per item
ItemSeparatorComponent Between rows only
ListHeaderComponent, ListFooterComponent, ListEmptyComponent Slots around and instead of rows
numColumns Grid (changing it needs a new key)
extraData Re-render rows when something outside data changes
onEndReached, onEndReachedThreshold Infinite scroll
refreshing, onRefresh Pull to refresh
getItemLayout Skip measuring for fixed-height rows
initialNumToRender, windowSize, maxToRenderPerBatch Window tuning
contentContainerStyle Padding and flexGrow: 1 for centered empty states

See FlatList Essentials, Fast Lists and SectionList and Pull to Refresh.

Task React Navigation Expo Router
Go to a screen navigation.navigate('Details', { id: 1 }) router.push('/details/1')
Add on top navigation.push('Details', { id: 2 }) router.push(...)
Go back navigation.goBack() router.back()
Replace current navigation.replace('Home') router.replace('/')
Back to first screen navigation.popToTop() router.dismissAll()
Read params route.params.id useLocalSearchParams<{ id: string }>()
Link element none (use Pressable) <Link href="/about">About</Link>
TSX
// React Navigation: typed native stack
type RootStackParamList = { Home: undefined; Details: { id: string } };
const Stack = createNativeStackNavigator<RootStackParamList>();

<NavigationContainer>
  <Stack.Navigator initialRouteName="Home">
    <Stack.Screen name="Home" component={HomeScreen} />
    <Stack.Screen name="Details" component={DetailsScreen} options={{ title: 'Details' }} />
  </Stack.Navigator>
</NavigationContainer>
TEXT
// Expo Router file layout
app/
  _layout.tsx        // root navigator
  index.tsx          // "/"
  (tabs)/_layout.tsx // a group that does not appear in the URL
  details/[id].tsx   // "/details/42"

See Stack Navigation, Route Params and Typed Navigation, Tab and Drawer Navigators and File-Based Routing with Expo Router.

Hooks and APIs worth memorizing

Name Returns or does
useWindowDimensions() { width, height, scale, fontScale }, updates on rotation
useColorScheme() 'light', 'dark' or null
useSafeAreaInsets() { top, right, bottom, left } from react-native-safe-area-context
useNavigation(), useRoute() Navigation object and current route
useFocusEffect(cb), useIsFocused() Run code when a screen gains or loses focus
Platform.OS, Platform.select({...}) Choose values per platform
Linking.openURL(url) Open a link, phone, mail or another app
Alert.alert(title, message, buttons) Native alert
AppState active, background changes
BackHandler.addEventListener('hardwareBackPress', fn) Android back button
Keyboard.dismiss() Hide the keyboard

See Platform APIs and Platform-Specific Code.

Style arrays and Platform.select are easy to forget the exact behavior of. The stand-in below reimplements both in a few lines: pick a platform and see which value wins.

Style arrays and Platform.select

Storage and data

TSX
import AsyncStorage from '@react-native-async-storage/async-storage';
import * as SecureStore from 'expo-secure-store';

await AsyncStorage.setItem('prefs', JSON.stringify({ theme: 'dark' }));
const prefs = JSON.parse((await AsyncStorage.getItem('prefs')) ?? '{}');
await AsyncStorage.removeItem('prefs');

await SecureStore.setItemAsync('refreshToken', token);       // Keychain / Keystore
const saved = await SecureStore.getItemAsync('refreshToken');

// Server state with TanStack Query
const { data, isPending, error, refetch } = useQuery({
  queryKey: ['posts'],
  queryFn: () => fetch(`${API}/posts`).then((r) => r.json()),
});
Data Store
Preferences, small caches AsyncStorage or MMKV
Tokens and secrets SecureStore
Large or relational data SQLite (expo-sqlite)
Data from a server Query cache (TanStack Query)

See Storing Data, Networking with fetch and Server State with TanStack Query.

Networking reminders: the Android emulator reaches your computer at 10.0.2.2, the iOS simulator at localhost, a real phone needs your computer's LAN address, and production traffic must use HTTPS.

Commands

Command What it does
npx create-expo-app@latest my-app New Expo project
npx expo start Start the dev server (--clear clears the Metro cache)
npx expo install <package> Install a version that matches your SDK
npx expo-doctor Diagnose dependency and config problems
npx expo prebuild Generate the native ios and android folders
npx expo run:ios, npx expo run:android Build and run a native app locally
eas build --platform ios --profile production Cloud build (android, all)
eas submit Upload a build to the stores
eas update --channel production --message "Fix typo" Publish an over-the-air update
npx react-native start, npx react-native run-android The bare CLI equivalents
adb reverse tcp:8081 tcp:8081 Let an Android device reach Metro over USB
adb logcat Android device logs

See Setting Up with Expo, Builds with EAS and Over-the-Air Updates.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the default flexDirection in React Native?

    React Native defaults to column, unlike CSS, where the default is row.
  2. 2. Which tool should hold a refresh token?

    SecureStore uses the iOS Keychain and Android Keystore. AsyncStorage is unencrypted.
  3. 3. What does the style array [base, isActive && active] produce when isActive is false?

    Falsy entries are skipped, and later entries override earlier ones when they set the same key.
  4. 4. How does an Android emulator reach a server running on your computer?

    Inside the Android emulator, localhost is the emulator itself. 10.0.2.2 is the alias for the host machine.

Summary

  • Native views (View, Text, Image) plus Flexbox (column by default) and plain-object styles are the foundation.
  • Pressable handles touch, FlatList handles long lists, and keys must be stable.
  • Navigation is a stack of screens: navigate, push, goBack, replace; Expo Router maps files to routes.
  • Preferences go in AsyncStorage or MMKV, secrets in SecureStore, server data in a query cache.
  • Know the Expo and EAS commands, and remember 10.0.2.2 for the Android emulator.

You have reached the end of the React Native tutorial. Revisit the exercises and the interview questions whenever you want a refresher, and keep building: the projects are the best way to turn all of this into habits.