We created this React Native Cheat Sheet initially for students of our React Native Bootcamp course.
But we're now sharing it with any and all Developers that want to learn and remember some of the React Native key information and concepts, and have a quick reference guide to the fundamentals of React Native.
We guarantee this is the best and most comprehensive React Native Cheat Sheet you can find.
Enter your email below and we'll send it to you 👇
Unsubscribe anytime.
If you’ve stumbled across this cheatsheet and are just starting to learn React Native, you've made a great choice!
If you're interested in becoming a Mobile Developer, React Native is definitely the way to go (in our opinion at least).
However, if you're stuck in an endless cycle of boring and outdated YouTube tutorials and want to start building real world projects, become a professional developer, have fun and actually get hired, then come join Zero To Mastery.
You'll efficiently learn React Native from actual industry professionals alongside 1,000s of students in our private Discord community (plus direct access to mentors and your instructors).
You'll not only learn to become a top 10% React Native Developer by learning advanced topics most courses don't cover. But you'll also build React Native projects that you'll be able to add to your portfolio and wow employers!
Just want the cheatsheet? No problem! Please enjoy and if you'd like to submit any suggestions, feel free to email us at support@zerotomastery.io
Expo CLI provides a convenient way to start React Native projects.
npm install -g expo-cli
expo init MyApp
cd MyApp
npm start
React Native provides a set of core components for building user interfaces.
View
: The fundamental component for building UI, similar to a div
in HTML.Text
: Used for displaying text.Image
: Displays images.ScrollView
: A scrollable container for views.TextInput
: For text input fields.TouchableOpacity
: For wrapping components to make them touch-responsive.import React from 'react';
import { View, Text, Image } from 'react-native';
const App = () => (
<View>
<Text>Hello, World!</Text>
<Image
source={{ uri: 'https://example.com/image.png' }}
style={{ width: 100, height: 100 }}
/>
</View>
);
export default App;
React Native uses JavaScript objects for styling, similar to inline styles in HTML but with a CSS-like syntax.
const styles = {
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
};
<View style={styles.container}>
<Text style={{ color: 'blue', fontSize: 20 }}>Styled Text</Text>
</View>
backgroundColor
).React Native uses Flexbox for layout, providing a powerful way to arrange components.
flexDirection
: Determines the primary axis ('row'
or 'column'
).justifyContent
: Aligns children along the primary axis.alignItems
: Aligns children along the secondary axis.flex
: Determines how a component grows or shrinks.<View style={{ flex: 1, flexDirection: 'row' }}>
<View style={{ flex: 1, backgroundColor: 'red' }} /><View style={{ flex: 2, backgroundColor: 'green' }} /><View style={{ flex: 3, backgroundColor: 'blue' }} />
</View>
Props are inputs to components, allowing data to be passed from parent to child.
const Greeting = (props) => (
<Text>Hello, {props.name}!</Text>
);
<Greeting name="Alice" />
State allows components to create and manage their own data.
import React, { useState } from 'react';
import { View, Text, Button } from 'react-native';
const Counter = () => {
const [count, setCount] = useState(0);
return (
<View>
<Text>You clicked {count} times</Text>
<Button onPress={() => setCount(count + 1)} title="Click me" />
</View>
);
};
Events are handled using callback functions passed as props.
<Button
onPress={() => {
alert('Button pressed!');
}}
title="Press Me"
/>
onPress
: Triggered when a component is pressed.onChangeText
: Used with TextInput
to handle text changes.onSubmitEditing
: Triggered when the user submits the text input.The optimal way to render scrolling lists of data, it has various properties that you can adjust and adapt to allow for more efficient rendering.
import { FlatList, Text } from 'react-native';
<FlatList
data={[{ key: 'Alice' }, { key: 'Bob' }]}
renderItem={({ item }) => <Text>{item.key}</Text>}
/>
For rendering sections with headers.
import { SectionList, Text } from 'react-native';
<SectionList
sections={[
{ title: 'A', data: ['Alice', 'Alan'] },
{ title: 'B', data: ['Bob', 'Bill'] },
]}
renderItem={({ item }) => <Text>{item}</Text>}
renderSectionHeader={({ section }) => <Text>{section.title}</Text>}
/>
React Navigation is the standard library for handling navigation in React Native apps. Make sure to utilize native stack navigator for the full native experience and performance benefits.
npm install @react-navigation/native
npm install @react-navigation/native-stack
expo install react-native-screens react-native-safe-area-context
import * as React from 'react';
import { Button, View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
const Stack = createNativeStackNavigator();
function HomeScreen({ navigation }) {
return (
<Button
title="Go to Details"
onPress={() => navigation.navigate('Details')}
/>
);
}
function DetailsScreen() {
return (
<View>
<Text>Details Screen</Text>
</View>
);
}
export default function App() {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Details" component={DetailsScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
Use the fetch
API or libraries like axios
for network requests.
import React, { useEffect, useState } from 'react';
import { FlatList, Text } from 'react-native';
const FetchExample = () => {
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://example.com/data')
.then((response) => response.json())
.then((json) => setData(json.items))
.catch((error) => console.error(error));
}, []);
return (
<FlatList
data={data}
renderItem={({ item }) => <Text>{item.name}</Text>}
keyExtractor={(item) => item.id.toString()}
/>
);
};
Use the Platform
module to conditionally render code based on the platform.
import { Platform, Text } from 'react-native';
const instructions = Platform.select({
ios: 'Press Cmd+R to reload',
android: 'Double tap R on your keyboard to reload',
});
<Text>{instructions}</Text>
Platform.OS
: Returns 'ios'
, 'android'
, or 'web'
.React Native provides the Animated
API for creating animations.
import React, { useRef, useEffect } from 'react';
import { Animated, Text } from 'react-native';
const FadeInView = (props) => {
const fadeAnim = useRef(new Animated.Value(0)).current; // Initial opacity value
useEffect(() => {
Animated.timing(fadeAnim, {
toValue: 1, // Fade to opacity 1
duration: 1000,
useNativeDriver: true,
}).start();
}, [fadeAnim]);
return (
<Animated.View style={{ opacity: fadeAnim }}>
{props.children}
</Animated.View>
);
};
<FadeInView>
<Text>Fading in</Text>
</FadeInView>;
React Native supports React Hooks for state and lifecycle management.
useState
import React, { useState } from 'react';
const [value, setValue] = useState(initialValue);
useEffect
import React, { useEffect } from 'react';
useEffect(() => {
// Perform side effects here
return () => {
// Cleanup if necessary
};
}, [dependencies]);
Install additional libraries using npm
or yarn
.
axios
npm install axios
import axios from 'axios';
axios
.get('https://example.com/data')
.then((response) => {
// Handle success
})
.catch((error) => {
// Handle error
});
console.log()
for debugging.Ctrl + M
(Cmd + M
on Mac) to open the developer menu.npm start
npm run android
npm run ios
expo build:android
expo build:ios
TypeScript adds optional static typing to JavaScript, which can help catch errors early and improve code quality.
To add TypeScript to a React Native project:
npx react-native init MyApp --template react-native-template-typescript
If you have an existing project:
npm install --save-dev typescript @types/react @types/react-native
import React from 'react';
import { Text, View } from 'react-native';
interface Props {
name: string;
}
const Greeting: React.FC<Props> = ({ name }) => (
<View>
<Text>Hello, {name}!</Text>
</View>
);
export default Greeting;
Testing ensures your app works as expected and reduces bugs.
React Native comes with Jest, a JavaScript testing framework.
npm install --save-dev jest @testing-library/react-native react-test-renderer
import React from 'react';
import renderer from 'react-test-renderer';
import App from '../App';
test('renders correctly', () => {
const tree = renderer.create(<App />).toJSON();
expect(tree).toMatchSnapshot();
});
For testing components with user interactions.
import React from 'react';
import { render, fireEvent } from '@testing-library/react-native';
import MyButton from '../MyButton';
test('Button presses correctly', () => {
const onPressMock = jest.fn();
const { getByText } = render(
<MyButton onPress={onPressMock} title="Press me" />
);
fireEvent.press(getByText('Press me'));
expect(onPressMock).toHaveBeenCalled();
});
Making your app accessible ensures it can be used by as many people as possible.
accessible
: Marks a component as accessible.accessibilityLabel
: Provides a readable label for screen readers.accessibilityHint
: Provides additional information about a component.<TouchableOpacity
accessible={true}
accessibilityLabel="Play Button"
accessibilityHint="Plays the current track"
onPress={handlePlay}
>
<Text>Play</Text>
</TouchableOpacity>
To access certain device features, you may need to request permissions.
PermissionsAndroid
(Android)import { PermissionsAndroid } from 'react-native';
async function requestCameraPermission() {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.CAMERA,
{
title: 'Camera Permission',
message: 'This app needs access to your camera',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log('You can use the camera');
} else {
console.log('Camera permission denied');
}
} catch (err) {
console.warn(err);
}
react-native-permissions
(Cross-platform)npm install react-native-permission
import { check, request, PERMISSIONS, RESULTS } from 'react-native-permissions';
async function checkCameraPermission() {
const result = await check(PERMISSIONS.ANDROID.CAMERA);
switch (result) {
case RESULTS.GRANTED:
console.log('Camera permission granted');
break;
case RESULTS.DENIED:
const requestResult = await request(PERMISSIONS.ANDROID.CAMERA);
if (requestResult === RESULTS.GRANTED) {
console.log('Camera permission granted');
}
break;
// Handle other cases
}
}
React Native provides access to various device APIs.
import Geolocation from '@react-native-community/geolocation';
Geolocation.getCurrentPosition(
(position) => {
console.log(position);
},
(error) => {
console.log(error);
},
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
);
import { CameraRoll } from '@react-native-community/cameraroll';
CameraRoll.getPhotos({
first: 20,
assetType: 'Photos',
})
.then((r) => {
this.setState({ photos: r.edges });
})
.catch((err) => {
console.log(err);
});
import { Clipboard } from 'react-native';
Clipboard.setString('Hello World');
Clipboard.getString().then((content) => {
console.log(content);
});
AsyncStorage is a simple, unencrypted, asynchronous, persistent, key-value storage system.
npm install @react-native-async-storage/async-storage
import AsyncStorage from '@react-native-async-storage/async-storage';
const storeData = async (value) => {
try {
await AsyncStorage.setItem('@storage_Key', value);
} catch (e) {
// saving error
}
};
const getData = async () => {
try {
const value = await AsyncStorage.getItem('@storage_Key');
if (value !== null) {
// value previously stored
}
} catch (e) {
// error reading value
}
};
Optimizing performance ensures your app runs smoothly.
PureComponent
or React.memo
Prevents unnecessary re-renders.
import React from 'react';
const MyComponent = React.memo(({ prop1, prop2 }) => {
// Component code
});
render
Pass functions defined outside render
to child components.
useCallback
and useMemo
Optimize expensive functions and computations.
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
const memoizedCallback = useCallback(() => {
doSomething(a, b);
}, [a, b]);
Support multiple languages in your app.
react-native-i18n
npm install react-native-i18n
import I18n from 'react-native-i18n';
I18n.fallbacks = true;
I18n.translations = {
en: { welcome: 'Welcome' },
fr: { welcome: 'Bienvenue' },
};
<Text>{I18n.t('welcome')}</Text>
react-native-localize
and i18n-js
A modern approach to internationalization.
npm install react-native-localize i18n-js
import * as RNLocalize from 'react-native-localize';
import i18n from 'i18n-js';
const locales = RNLocalize.getLocales();
if (Array.isArray(locales)) {
i18n.locale = locales[0].languageTag;
}
i18n.fallbacks = true;
i18n.translations = {
en: { welcome: 'Welcome' },
fr: { welcome: 'Bienvenue' },
};
<Text>{i18n.t('welcome')}</Text>
Handling errors gracefully improves user experience.
Catch JavaScript errors in components.
import React from 'react';
import { View, Text } from 'react-native';
class ErrorBoundary extends React.Component {
state = { hasError: false };
componentDidCatch(error, info) {
// Log error
this.setState({ hasError: true });
}
render() {
if (this.state.hasError) {
return <Text>Something went wrong.</Text>;
}
return this.props.children;
}
}
<ErrorBoundary>
<MyComponent />
</ErrorBoundary>;
Use try-catch blocks in async functions.
try {
const response = await fetchData();
} catch (error) {
console.error(error);
}
Following best practices helps maintain code quality.
Organize your files logically.
- src/
- components/
- screens/
- navigation/
- services/
- assets/
Use ESLint and Prettier.
npm install --save-dev eslint prettier eslint-config-prettier eslint-plugin-prettier
Create components that can be reused throughout your app.
Use comments and documentation to explain complex logic.
Ensure component props are correctly used.
import PropTypes from 'prop-types';
MyComponent.propTypes = {
name: PropTypes.string.isRequired,
};
This React Native cheat sheet provides a comprehensive reference to React Native concepts, including testing, accessibility, permissions, device APIs, offline storage, performance optimization, internationalization, error handling, and best practices. For more detailed information, refer to the official React Native documentation and resources.