Bookmarks
ReferenceMobile developmentVerified

React Native

React Native is a framework for building Android and iOS apps with React. This reference covers components, Flexbox, navigation, data, native modules and Expo.

checked 1 Nov · next check 8 Nov · 49 min read

Sections
12
Reading
49 min
Current version
0.88.1
Written from
reactnative.dev/docs/getting-started

Check status of the reference

Verified 1 Nov · next check 8 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What React Native is and how it works

React Native is an open-source framework for building Android and iOS apps with React. You describe the interface with React components in JavaScript or TypeScript, and the screen shows real native platform views, not a web page.

Choose React Native when your team knows React and you need to ship one app for Android and iOS with system interface elements. The <Text> component becomes TextView on Android and UITextView on iOS, so the app looks and behaves as if it were written in Kotlin or Swift. Anything JavaScript cannot do is added with native code: your own modules and components in Kotlin, Java, Swift or Objective-C.

Since version 0.82, React Native runs only on the New Architecture. The Hermes engine executes your app code and React, and they talk to the native side through JSI (JavaScript Interface): JavaScript holds a reference to a C++ object and calls its methods directly, without serialisation. JSI replaced the old asynchronous bridge that passed messages back and forth. The Fabric renderer, which turns components into native views, and Turbo Modules, the native modules of the New Architecture, both work through JSI.

The New Architecture has no asynchronous bridge between JavaScript and the native side.

How a component reaches the screen

The renderer takes every interface update through three phases:

  1. Render. React calls your components and builds the React Element Tree. For each host component, such as View or Text, the renderer immediately creates a node of the React Shadow Tree in C++. This usually happens on the JavaScript thread.
  2. Commit. Yoga calculates the size and position of each node, and the new tree becomes the next one to mount. The platform itself measures text and text inputs. This phase usually runs asynchronously on a background thread.
  3. Mount. The renderer compares the new tree with the one on screen and gets a list of operations (createView, updateView, removeView), which it applies to the native views on the UI thread.

Trees are never changed in place. When state updates, React copies only the changed nodes and the path from them to the root, while unchanged nodes are shared between the old and new trees. The result is a single native operation, for example updateView for a view whose colour changed.

How Expo differs from React Native without a framework

For a new app, the official documentation recommends a React Native framework, a set of tools and APIs on top of React Native, and suggests starting with Expo. The Expo team also makes EAS, optional services for every stage of development. Without a framework, you create the project with the React Native Community CLI and have to assemble navigation, device API access and native dependencies from libraries yourself.

AspectExpoWithout a framework
What you get from the startfile-based routing, a standard library of native modules, development toolsReact Native itself; everything else is your own solutions or libraries you pick
Native codeplugins modify the native projects, so you don’t need to maintain the android and ios files by handyou edit the Android and iOS projects in Android Studio and Xcode
When to choose ita new app; this is the documentation’s recommendationspecial constraints that a framework doesn’t cover, or your own framework

Choose Expo for a new app. Work without a framework only when your app has unusual requirements and your team is ready to maintain its own scaffolding. The choice between React Native, Flutter and native development is covered in the Flutter reference, in the section “What Flutter is and how it works”.

What to know first

  • Components, props, state and effects: see the React reference, as React Native uses the same concepts.
  • The language and asynchronous code: see the JavaScript reference; for types, the TypeScript reference.
  • HTTP requests and status codes: see the HTTP and REST reference.

Section sources

the section is written from these pages

Cheat sheet

Everyday components, styles and commands; each line is explained in its own section. Run the commands in the Expo project directory.

Components

TaskComponent
Layout containerView
Text: strings go only inside itText
ImageImage
Text inputTextInput
Press handling for any elementPressable
Scrolling for a small amount of contentScrollView
Long listFlatList
List with sectionsSectionList (similar to FlatList)
Styles in one placeStyleSheet.create({ ... })

Styles and layout

TaskHow to write it
Fill all available spaceflex: 1
Children in a rowflexDirection: 'row'
Children in a column (default)flexDirection: 'column'
Centre on the main axisjustifyContent: 'center'
Centre on the cross axisalignItems: 'center'
Edges with equal spacingjustifyContent: 'space-between'
Gap between childrengap: 8
Wrap onto a new lineflexWrap: 'wrap'
Half the parent’s widthwidth: '50%'
Position independently of siblingsposition: 'absolute', top: 0, right: 0

Platform

TaskHow to write it
Detect the platformPlatform.OS === 'ios'
A value for each platformPlatform.select({ ios: 20, android: 16, default: 16 })
Android API levelPlatform.Version
A file for iOS or Android onlybutton.ios.tsx, button.android.tsx
One file for Android and iOS, a separate one for the webbutton.native.tsx and button.tsx

Expo commands

TaskCommand
Create a projectnpx create-expo-app@latest my-app --template default@sdk-58
Start the development servernpx expo start
Open on Android and iOS from the terminala and i in the npx expo start terminal
Open React Native DevToolsj in the npx expo start terminal
Connect through a tunnelnpx expo start --tunnel
Install a compatible package versionnpx expo install expo-secure-store
Check package versionsnpx expo install --check
Fix package versionsnpx expo install --fix

Native build

TaskCommand
Build and run on Androidnpx expo run:android
Build and run on iOSnpx expo run:ios
Run on a connected phonenpx expo run:android --device
Release build for testing on Androidnpx expo run:android --variant release
Create the android and ios directoriesnpx expo prebuild
Recreate them from scratchnpx expo prebuild --clean
Build for the app stores with EASeas build --platform all

Section sources

the section is written from these pages

Installation and first run

The official documentation recommends starting with the Expo framework: npx create-expo-app@latest creates the project and npx expo start starts the development server. You see the result right away: the app opens on your phone via a QR code, or in an emulator.

What you need

  • Node.js, an LTS version.
  • macOS, Windows (PowerShell or WSL 2) or Linux.
  • For your first steps, a phone with the Expo Go app.
  • For your own native build, Android Studio with an emulator for Android and Xcode with iOS Simulator for iOS.

Creating a project

bashin a terminal
npx create-expo-app@latest --template default@sdk-58# my-app is the name you entered when creating the projectcd my-appnpx expo start

Running on a phone and in an emulator

npx expo start prints a QR code. Scan it with a phone that has Expo Go installed, or press a to open the app in an Android emulator and i for iOS Simulator. The computer and the phone must be on the same Wi-Fi network. On public networks the router often blocks devices from reaching each other; in that case, start the server through a tunnel. It is noticeably slower than a local network connection.

bashin the project directory
npx expo start --tunnel

On an iPhone, Expo Go opens the project only if Expo CLI and Expo Go are signed in to the same Expo account: run npx expo login and sign in to Expo Go with the same account. Code changes appear on the device by themselves; if they don’t, shake the device to open the Dev Menu and turn on Fast Refresh.

Expo Go and development builds

Expo Go is a ready-made app from the store for learning and trying out Expo. A development build is a build of your own app with Expo’s development tools: add expo-dev-client and you can use any native library and change any native setting. For an app that is going to the stores, the Expo documentation recommends a development build.

bashin the project directory
npx expo install expo-dev-clientnpx expo run:android

npx expo run:android and npx expo run:ios create the native android and ios directories if they don’t exist, build the app, install it in the emulator or simulator and start the development server. For a phone connected over USB, add --device. Without a paid Apple Developer account, building for an iPhone is possible only this way, locally.

Rebuild the native app only when the native side changes: you installed or updated a library with native code, changed app.json or moved to a new Expo SDK. In that case, recreate the directories and build again; npx expo start picks up TypeScript changes on its own.

bashin the project directory
npx expo prebuild --cleannpx expo run:android

Your first project

textdefault project
my-app/├── src/│   ├── app/│   │   ├── _layout.tsx│   │   ├── index.tsx│   │   └── explore.tsx│   ├── components/│   ├── constants/│   └── hooks/├── assets/├── scripts/├── app.json├── package.json└── tsconfig.json
  • src/app/ holds the screens: the file structure defines the navigation. index.tsx and explore.tsx are two screens, and _layout.tsx is the layout that builds the tabs.
  • src/components/, src/constants/ and src/hooks/ hold the rest of the app code.
  • app.json is the Expo app configuration: after you change it, rebuild the native app.
  • package.json lists the dependencies and npm scripts.

Without a framework

If your app has special constraints, create the project without Expo using the React Native Community CLI. You then set up Android Studio and Xcode by hand. The Metro server runs in one terminal and the app in another.

bashin a terminal
npx @react-native-community/cli@latest init AwesomeProjectcd AwesomeProjectnpm start
bashin a second terminal
npm run android

Section sources

the section is written from these pages

Core components

Core components are the ready-made React Native components backed by platform views: View is a ViewGroup on Android and a UIView on iOS. There are no HTML tags here: you build a screen from View, Text, Image, TextInput and lists.

Components backed by Android and iOS views are called native components. React Native creates these views at runtime, so the app looks and works like an ordinary native one. If the ready-made ones aren’t enough, you write your own native components in Kotlin or Java and in Swift or Objective-C.

ComponentAndroidiOSWeb equivalent
ViewViewGroupUIView<div> without scrolling
TextTextViewUITextView<p>
ImageImageViewUIImageView<img>
ScrollViewScrollViewUIScrollView<div>
TextInputEditTextUITextField<input type="text">

Images from the project and from the network, using the Image component, are covered in the section “Data: networking and storage”.

View and Text

View is a container: Flexbox layout, styles, touch handling and accessibility settings all work in it. Put text only inside Text: a string directly in a View throws an exception. Inside Text, text layout applies instead of Flexbox: nested Text components wrap as one line of text and inherit the style of the parent Text.

tsxgreeting.tsx
import { Text, View } from 'react-native'; export function Greeting() {  return (    <View style={{ padding: 16 }}>      <Text style={{ fontSize: 18 }} numberOfLines={2}>        Hello, <Text style={{ fontWeight: 'bold' }}>Aziza</Text>      </Text>    </View>  );}

numberOfLines={2} truncates the text with an ellipsis after the second line. There is no font shared by a whole subtree, like the inherited font-family in CSS, and fontFamily accepts a single font name. Make your own component, for example AppText, with the font you need and use it everywhere.

Presses: Pressable

Pressable wraps any element and tracks the stages of a press: onPressIn when the finger touches, onPressOut when it lifts, then onPress. If the finger stays down for more than 500 ms, onLongPress fires instead of onPress; delayLongPress changes the threshold. hitSlop extends the touch area beyond the element’s bounds, and style can be a function that receives { pressed }.

tsxsave-button.tsx
import { Pressable, Text } from 'react-native'; export function SaveButton({ onSave }: { onSave: () => void }) {  return (    <Pressable      onPress={onSave}      hitSlop={8}      style={({ pressed }) => ({ opacity: pressed ? 0.5 : 1 })}    >      <Text>Save</Text>    </Pressable>  );}

Text input: TextInput

TextInput is a controlled component: if you pass value, the native field always shows that value. New text arrives as a string in onChangeText, and you store it in state. onSubmitEditing fires when the keyboard’s submit key is pressed.

tsxemail-field.tsx
import { useState } from 'react';import { TextInput } from 'react-native'; export function EmailField() {  const [email, setEmail] = useState('');  return (    <TextInput      value={email}      onChangeText={setEmail}      placeholder="E-mail"      keyboardType="email-address"      autoCapitalize="none"    />  );}
PropWhat it doesDefault
keyboardTypekeyboard: numeric, email-address, phone-pad, urldefault
autoCapitalizecapitalisation: characters, words, sentences, nonesentences
secureTextEntryhides the input, for passwords; doesn’t work with multilinefalse
placeholdertext shown while the field is empty—
multilinemulti-line fieldfalse
maxLengthmaximum text length—

ScrollView or FlatList

ScrollView is a general-purpose scrolling container for several components and views. For long lists of data there is FlatList: it asynchronously renders items outside the visible area to save memory and scroll smoothly. The trade-off is that very fast scrolling can briefly show blank space, and the internal state of an item that has left the window is lost: keep data in data or in an external store.

Lists: FlatList

FlatList requires two props: data, an array of items, and renderItem, a function that receives { item, index } and returns the item’s markup. The list takes the React key from item.key, then from item.id, and from the index if neither exists; keyExtractor specifies a different field. FlatList is a PureComponent and re-renders only when its props change, so pass anything renderItem depends on besides data in extraData.

PropWhat it does
dataarray of list items
renderItemrenders an item; receives { item, index }
keyExtractorunique key of an item
extraDataexternal value whose change makes the list re-render
ItemSeparatorComponentseparator between items
ListEmptyComponentwhat to show when the list is empty
ListHeaderComponent, ListFooterComponentlist header and footer
numColumnsseveral columns of equal height
onRefresh, refreshingpull-to-refresh
horizontalhorizontal list

Example: a list with search

tsxsrc/app/index.tsx
import { useState } from 'react';import {  FlatList, Pressable, StyleSheet, Text, TextInput, View,} from 'react-native'; const CITIES = ['Tashkent', 'Samarkand', 'Bukhara', 'Namangan']; export default function CitiesScreen() {  const [query, setQuery] = useState('');  const [selected, setSelected] = useState<string | null>(null);  const q = query.trim().toLowerCase();  const found = CITIES.filter((city) => city.toLowerCase().includes(q));  return (    <View style={styles.screen}>      <TextInput value={query} onChangeText={setQuery}        placeholder="Search" style={styles.input} />      <FlatList        data={found}        keyExtractor={(city) => city}        extraData={selected}        renderItem={({ item }) => (          <Pressable onPress={() => setSelected(item)}>            <Text style={[styles.row, item === selected && styles.active]}>              {item}            </Text>          </Pressable>        )}        ListEmptyComponent={<Text style={styles.row}>Nothing found</Text>}      />    </View>  );} const styles = StyleSheet.create({  screen: { flex: 1, padding: 16, gap: 8 },  input: { borderWidth: 1, borderRadius: 8, padding: 12 },  row: { paddingVertical: 12, fontSize: 16 },  active: { fontWeight: 'bold' },});

The list is filtered on every keystroke: found is recalculated from query. The items are strings with no key or id fields, so keyExtractor supplies the key. The selected city is stored in selected, which isn’t part of data: without extraData={selected} the highlight wouldn’t re-render. ListEmptyComponent shows a row when nothing is found.

Section sources

the section is written from these pages

Styles and Flexbox layout

Styles in React Native are JavaScript objects passed to the style prop. Names and values are close to CSS but written in camelCase: backgroundColor instead of background-color. Layout uses Flexbox, with different defaults from the browser: the main axis is vertical by default.

All core components accept a style prop, either an object or an array of styles. In an array the last style wins, so arrays are used for variants: a base style plus an “active” one. When there are many styles, collect them in one place with StyleSheet.create. To pass styles down, as the cascade does in CSS, have the component accept style from its parent and hand it to its children.

tsxbadge.tsx
import { StyleSheet, Text, View } from 'react-native'; export function Badge({ active }: { active: boolean }) {  return (    <View style={[styles.badge, active && styles.active]}>      <Text style={styles.label}>New</Text>    </View>  );} const styles = StyleSheet.create({  badge: { paddingHorizontal: 8, borderRadius: 4, backgroundColor: '#e5e7eb' },  active: { backgroundColor: '#93c5fd' },  label: { fontSize: 12 },});

Flexbox: differences from CSS

Flexbox in React Native works as in CSS, but the defaults differ. The main difference is that flexDirection is column by default, so children stack from top to bottom and justifyContent aligns them vertically. To lay items out in a row, set flexDirection: 'row'.

CSS default on the left, React Native on the right; justifyContent always works along the main axis.
PropertyReact NativeCSS in the browser
flexDirectioncolumnrow
alignContentflex-startstretch
flexShrink01
flexa single numbera shorthand with several values

Core properties

PropertyWhat it doesDefault
flexdivides the free space along the main axis in proportion to the numbers: 1, 2 and 3 give 1/6, 2/6 and 3/6—
flexDirectiondirection of the main axis: row, column, row-reverse, column-reversecolumn
justifyContentalignment along the main axis: flex-start, center, flex-end, space-between, space-around, space-evenlyflex-start
alignItemsalignment along the cross axisstretch
alignSelfthe same for a single child; overrides the parent’s alignItems—
flexWrapwraps children onto new linesno wrapping
gap, rowGap, columnGapspacing between children: a number or a percentage—
positionrelative, absolute or staticrelative
tsxtoolbar.tsx
import { StyleSheet, Text, View } from 'react-native'; export function Toolbar() {  return (    <View style={styles.row}>      <Text style={styles.title}>Inbox</Text>      <Text>Edit</Text>    </View>  );} const styles = StyleSheet.create({  row: {    flexDirection: 'row',    justifyContent: 'space-between',    alignItems: 'center',    gap: 12,    padding: 16,  },  title: { flexShrink: 1, fontSize: 20 },});

The title and the “Edit” label sit in a row, are pushed to the edges and are centred vertically. alignItems: 'stretch' stretches children along the cross axis only if they have no fixed size on that axis.

Sizes

Sizes in React Native are plain numbers without units, in density-independent pixels. Fixed width and height suit elements whose size does not depend on the screen, although the physical size may differ slightly between devices. flex: 1 stretches an element to fill the free space and shares it equally with siblings that have the same flex. Percentages (width: '50%') are calculated from the parent’s size.

The useWindowDimensions hook returns the window size: width, height, scale (the pixel density) and fontScale (the font scale from the system settings). The values update automatically when the window size or font scale changes, and the component re-renders.

tsxscreen-info.tsx
import { Text, useWindowDimensions } from 'react-native'; export function ScreenInfo() {  const { width, height, fontScale } = useWindowDimensions();  const columns = width >= 600 ? 3 : 2;  return (    <Text>      {width}×{height}, {columns} columns, font ×{fontScale}    </Text>  );}

Safe area

The safe area is the part of the screen not covered by navigation bars, the tab bar, rounded corners or the camera cut-out. The SafeAreaView component from react-native is deprecated, and it only worked on iOS 11 and later. The official replacement is the react-native-safe-area-context library.

Colours

A colour is a string, as in CSS: '#ff00ff', 'rgb(255, 0, 255)', 'hsl(360, 100%, 100%)' or a colour name such as 'mediumturquoise'. React Native accepts only lower-case names. PlatformColor provides the platform’s system colours: the element looks native and reads correctly in both themes.

Dark mode

The useColorScheme hook returns the device theme, 'light' or 'dark', and updates the component when the user changes the theme in settings. Choosing the colours is up to you: keep them in two sets and pick a set by the theme value. For a light and dark colour pair on iOS there is also DynamicColorIOS.

tsxtheme.tsx
import { Text, useColorScheme } from 'react-native'; const COLORS = { light: '#111827', dark: '#f9fafb' }; export function Headline() {  const scheme = useColorScheme() ?? 'light';  return <Text style={{ color: COLORS[scheme] }}>Settings</Text>;}

Section sources

the section is written from these pages

Data: network and storage

Network data is loaded with fetch, as in the browser. On the device, data is stored according to how secret it is: ordinary data in Async Storage, tokens and passwords in the Keychain on iOS and the Keystore on Android. Never keep API keys in the app code: anyone can read them.

fetch requests

fetch returns a promise. Always handle errors thrown by fetch: without a catch they disappear silently. The second argument carries the method, headers and request body. How Request, Response and status codes work is covered in the JavaScript reference, section “fetch requests”.

typescriptsrc/api/client.ts
type Movie = { id: string; title: string }; export async function loadMovies(): Promise<Movie[]> {  const response = await fetch('https://api.example.com/movies');  if (!response.ok) {    throw new Error(`HTTP ${response.status}`);  }  const json = await response.json();  return json.movies;} export async function createOrder(productId: string) {  await fetch('https://api.example.com/orders', {    method: 'POST',    headers: {      Accept: 'application/json',      'Content-Type': 'application/json',    },    body: JSON.stringify({ productId, count: 1 }),  });}

Start loading when a screen opens from an effect, as described in the React reference, section “Effects”. Besides fetch, React Native has XMLHttpRequest, which libraries such as axios use, and WebSocket for two-way communication over a single TCP connection.

Differences from the browser

  • There is no CORS: a native app has no such policy, and requests are not checked against it as they are in a browser.
  • iOS requires HTTPS: App Transport Security (ATS) blocks http:// requests. Add an exception in Info.plist under NSAppTransportSecurity, and only for the domains you need through NSExceptionDomains, not NSAllowsArbitraryLoads for everything: App Store review will ask you to justify turning ATS off.
  • Android from API 28 also blocks unencrypted HTTP; the android:usesCleartextTraffic attribute in the manifest allows it.
  • In fetch, redirect: 'manual' and credentials: 'omit' do not work, and on Android headers with the same name collapse into the last one. Cookie-based authentication is unreliable.

Images from the project and from the network

Include an image from the project with require: the bundler knows its size and picks the @2x or @3x file for the screen density. The name in require must be known in advance; you cannot build the path from variables. The size of a network image is not known in advance, so set width and height manually, and use an https:// address, as ATS requires on iOS.

tsxavatar.tsx
import { Image, View } from 'react-native'; export function Avatar({ url }: { url: string }) {  return (    <View style={{ flexDirection: 'row', gap: 8 }}>      <Image source={require('./img/check.png')} />      <Image        source={{ uri: url }}        style={{ width: 48, height: 48, borderRadius: 24 }}      />    </View>  );}

The source of a network image can also carry the request’s method, headers and body, for example an authorisation header.

Where to store data

StorageWhat to keep thereNotes
Async Storage (community library)non-secret data between launches: settings, cache, statean asynchronous, unencrypted key–value store; each app has its own
Keychain Services (iOS)tokens, passwords, certificatesfor small pieces of secret data
Encrypted Shared Preferences and Keystore (Android)tokens and cryptographic keysplain Shared Preferences are not encrypted; the Keystore makes keys harder to extract
expo-secure-storetokens in an Expo projectAndroid: SharedPreferences encrypted with a Keystore key; iOS: Keychain

React Native has no built-in API for the Keychain and Keystore, so use a wrapper library such as expo-secure-store or react-native-keychain. In an Expo project:

bashin the project directory
npx expo install expo-secure-store
typescriptsrc/auth/token.ts
import * as SecureStore from 'expo-secure-store'; export async function saveToken(token: string) {  await SecureStore.setItemAsync('session_token', token);} export function readToken() {  return SecureStore.getItemAsync('session_token');} export async function signOut() {  await SecureStore.deleteItemAsync('session_token');}

A key may contain Latin letters, digits, ., - and _. On Android, values are deleted with the app, while on iOS they can survive a reinstall with the same bundle ID; do not rely on that. The platform may reject very large values: some iOS versions did not accept more than about 2048 bytes.

Data security

  • If the app needs a third-party service’s secret key, put your own server or a serverless function between them: it adds the key to the request, and the key never reaches the app.
  • Do not put tokens or personal data in state that is saved to Async Storage as a whole, and do not send them to monitoring services such as Sentry and Crashlytics.
  • Do not pass secrets in deep links (myapp://...): another app can register the URL scheme and intercept the link. On iOS, universal links are safer.
  • For OAuth 2 sign-in, use the system browser and PKCE: a redirect scheme into the app is not unique, and PKCE ensures that the same client exchanges the code for a token. The react-native-app-auth library wraps the native AppAuth for iOS and Android, opens sign-in in a system browser tab rather than a web view, and supports PKCE.
  • Call the API over HTTPS only. Certificate pinning (SSL pinning) protects against spoofing with a fake root certificate on the device. Server certificates change every 1–2 years, and an app with an outdated pinned certificate stops working.

The protocol itself is covered in the OAuth and OIDC reference, section “Flows: authorization code, PKCE and others”.

Section sources

the section is written from these pages

Platform-specific code and native modules

Platform-specific code is needed where Android and iOS must behave differently: the Platform module handles small differences, and separate .ios.tsx and .android.tsx files handle large ones. A platform API that exists neither in React Native nor in libraries is exposed through your own native module.

The Platform module

Platform.OS is 'ios' or 'android'. Platform.select takes an object with the keys ios, android, native and default and returns the value for the current platform: on a phone it tries the platform key first, then native, then default. On Android, Platform.Version is the API level, for example 34; on iOS it is a string with the OS version.

typescriptheader-styles.ts
import { Platform, StyleSheet } from 'react-native'; export const styles = StyleSheet.create({  header: {    paddingTop: Platform.OS === 'ios' ? 20 : 0,    ...Platform.select({      ios: { shadowOpacity: 0.2, shadowRadius: 4 },      android: { elevation: 4 },      default: {},    }),  },}); export const oldAndroid = Platform.OS === 'android' && Platform.Version < 30;

Per-platform files

If there are many differences, split the component into two files, big-button.ios.tsx and big-button.android.tsx, and import it without the platform suffix: the bundler picks the right file. The .native.tsx suffix means “Android and iOS”: use it when code is shared with the web, where the web bundler takes the file without a suffix.

tsxscreen.tsx
// Metro picks big-button.ios.tsx or big-button.android.tsximport BigButton from './big-button';

When you need native code

Write native code when you need a platform API that is not in React Native or in existing libraries, or when you already have code in Kotlin, Java, Swift, Objective-C or C++. There are two kinds of extension. A native module is functions and objects without a UI: storage, notifications, network events. A native component is a platform view that looks like a React component in JavaScript.

The earlier Legacy Native Modules and Legacy Native Components are deprecated. Many such libraries also work in the New Architecture through interop layers, but it is more reliable to use a library version that supports the New Architecture, a different library, or to move the code to Turbo Native Modules and Fabric Native Components.

A Turbo Native Module step by step

A Turbo Native Module is a native module of the New Architecture. It is based on a typed specification in TypeScript or Flow: Codegen generates interfaces for Android and iOS from it, you implement them in the platform languages, and JavaScript calls the methods through JSI (the JavaScript Interface).

Codegen runs on its own: as a Gradle task on Android and during CocoaPods installation on iOS.
  1. In the app root, create a specs directory and a specification file. The module name starts with Native: NativeSettings.ts.
  2. In package.json, add a codegenConfig section: the specification name, the type modules, the specs directory, a Java package for Android and a provider class for iOS.
  3. Build the project: Codegen runs as the Gradle task generateCodegenArtifactsFromSchema on Android and during bundle exec pod install on iOS.
  4. Implement the interface Codegen created: on Android, a Kotlin or Java class and a package (BaseReactPackage) that registers the module; on iOS, an Objective-C++ class (a .mm file).
  5. Call the module’s methods from JavaScript through the object the specification exports.
typescriptspecs/NativeSettings.ts
import type { TurboModule } from 'react-native';import { TurboModuleRegistry } from 'react-native'; export interface Spec extends TurboModule {  getString(key: string): string | null;  setString(key: string, value: string): void;} export default TurboModuleRegistry.getEnforcing<Spec>('NativeSettings');
jsonpackage.json, excerpt
{  "codegenConfig": {    "name": "NativeSettingsSpec",    "type": "modules",    "jsSrcsDir": "specs",    "android": {      "javaPackageName": "com.myapp.settings"    },    "ios": {      "modulesProvider": { "NativeSettings": "RCTNativeSettings" }    }  }}
kotlinNativeSettingsModule.kt
package com.myapp.settings import android.content.Contextimport com.facebook.react.bridge.ReactApplicationContext class NativeSettingsModule(context: ReactApplicationContext) :  NativeSettingsSpec(context) {   private val prefs =    context.getSharedPreferences("settings", Context.MODE_PRIVATE)   override fun getName() = NAME   override fun getString(key: String): String? = prefs.getString(key, null)   override fun setString(key: String, value: String) {    prefs.edit().putString(key, value).apply()  }   companion object {    const val NAME = "NativeSettings"  }}
tsxApp.tsx
import NativeSettings from './specs/NativeSettings'; NativeSettings.setString('theme', 'dark');const theme = NativeSettings.getString('theme');

getEnforcing throws an exception if the module is not found; in that case TurboModuleRegistry.get returns null.

Custom views: Fabric Native Components

A custom UI element, for example a wrapper around Android’s WebView and iOS’s WKWebView, is written as a Fabric Native Component. The process is the same: a specification in TypeScript or Flow, Codegen, the native implementation, and use in the app. Name the specification file with the suffix NativeComponent, for example WebViewNativeComponent.ts: Codegen finds it by that suffix.

Expo modules

In an Expo project you can write a native module with the Expo Modules API in Swift and Kotlin: there is less boilerplate, and performance is comparable to Turbo Modules, since both work through JSI. Choose Turbo Modules if the module is written in C++ or must not depend on the expo package. Kotlin and Swift syntax is covered in the references “Android and Kotlin” and “iOS and Swift”.

Section sources

the section is written from these pages

Debugging and performance

Debugging starts with the Dev Menu, which opens React Native DevTools and the performance monitor. JavaScript errors and warnings appear on screen in LogBox. All of this works only in development builds and is disabled in release.

Dev Menu

WhereHow to open
Phoneshake the device
iOS SimulatorCtrl + Cmd + Z or Device → Shake
Android emulatorCmd + M on macOS, Ctrl + M on Windows and Linux
Android from a terminaladb shell input keyevent 82

Open React Native DevTools with “Open DevTools” in the menu, or press j in the development server terminal.

Fast Refresh shows code changes in the running app. It is on by default, most edits appear within a second or two, and the state of useState and useRef is preserved between edits. If a file exports anything besides a component, Fast Refresh reruns it along with the modules that import it, or does a full reload, so move such exports into a separate file.

React Native DevTools

React Native DevTools is the built-in debugger, based on the Chrome DevTools interface. It debugs JavaScript and React but does not replace native tools: debug native module code in Android Studio and Xcode.

PanelWhat it offers
Consolelogs with filters, expression evaluation, Live Expressions
Sourcessource files and breakpoints; a debugger; statement in code sets a breakpoint immediately
Network, since 0.83fetch(), XMLHttpRequest and <Image> requests: headers, timings, responses; Expo has its own Expo Network panel
Performance, since 0.83a trace: JavaScript execution, React tracks, network, custom marks
Memoryheap snapshots and memory leak hunting
Componentsthe component tree, props and state, live editing, highlighting of re-renders
Profilerrender times of components and React commits

If the app was closed, rebuilt or crashed, or Metro was stopped, DevTools shows “Debugging connection was closed”. Fix the cause and click “Reconnect DevTools”.

LogBox: errors on screen

A fatal error, such as a syntax error, opens LogBox full screen with the location of the error. You can’t dismiss it: it closes by itself once the error is fixed and the code reloads. Errors from the console appear as a notification with a red badge and a counter, warnings with a yellow one. While DevTools is open, LogBox hides everything except fatal errors, so the full list is in the DevTools console.

tsxApp.tsx
import { LogBox } from 'react-native'; // noisy warning from a third-party libraryLogBox.ignoreLogs(['Deprecation warning:', /^Legacy prop /]);

LogBox.ignoreAllLogs() hides all notifications, for example while demonstrating the app.

Debugging release builds

In release, the call stack is minified: instead of a file name and line you see p@1:132161. metro-symbolicate and a source map can translate it back (symbolicate it). Source maps are enabled by default on Android and disabled on iOS: add SOURCEMAP_FILE to the “Bundle React Native code and images” build phase in Xcode. The map must match exactly the commit the crashed app was built from.

bashin the project directory
adb logcat -d | npx metro-symbolicate \  android/app/build/generated/sourcemaps/react/release/index.android.bundle.map

Performance

The interface looks smooth at 60 frames per second, which leaves 16.67 ms per frame. The performance monitor, the “Perf Monitor” item in the Dev Menu, shows two frame counters. JS is the JavaScript thread, where React, app logic and touch handling run. UI is the platform’s main thread. If the JavaScript thread is busy for longer than a frame, the frame is dropped: JavaScript-driven animations freeze and touch response lags. ScrollView scrolling and native-stack transitions continue, because they run on the main thread.

SymptomWhat to do
Everything is slow in development modejudge speed in release only: development mode puts a heavy load on the JavaScript thread
A release build with console.log is slowremove console.* calls before building, for example with the babel-plugin-transform-remove-console plugin
A long FlatList is slowset getItemLayout if item sizes are known in advance
Transitions stutter during heavy workdefer the work until idle with requestIdleCallback; for animations, use useNativeDriver: true in Animated or LayoutAnimation
A tap responds with a delaywrap the heavy action in onPress in requestAnimationFrame
Animating the size of an Image is slow on iOSanimate transform: [{ scale }] instead of width and height

Hermes

Hermes is a JavaScript engine optimised for React Native. It is enabled by default, and its version is built together with each React Native release. Compared with JavaScriptCore, Hermes usually starts the app faster, uses less memory and reduces app size. In a release build, JavaScript is precompiled to Hermes bytecode.

javascriptApp.js
const isHermes = () => !!global.HermesInternal;console.log('Hermes:', isHermes());

Section sources

the section is written from these pages

Building and publishing

Stores accept only signed release builds: Google Play takes an AAB file signed with an upload key, and the App Store takes an archive signed with an Apple certificate. In an Expo project, EAS Build produces both builds and eas submit sends them to the stores.

With Expo: EAS Build and EAS Submit

EAS Build produces a file that is ready to submit and, if you allow it, creates the signing credentials itself: the Android keystore is stored on EAS servers. You need an Expo account and, to publish, membership of the Google Play Developer or Apple Developer Program.

bashin the project directory
npm install --global eas-clieas logineas build:configureeas build --platform androideas build --platform ios

eas build --platform all builds both platforms at once. eas submit uploads the finished build: the .aab to Google Play Console and the .ipa to App Store Connect, and for iOS this works from Windows and Linux too.

bashin the project directory
eas submit --platform androideas submit --platform ios

For a new app, eas submit puts the first build into Google Play internal testing. An iOS build appears in TestFlight after 10–15 minutes of processing, and reaches the App Store only after you fill in the app details, select the build and submit it for App Review. EAS Submit does not upload the description or screenshots.

Versions and build numbers

An app has two numbers. The user-facing version is version in app.json; on Android it is versionName, on iOS CFBundleShortVersionString. The build number for the store is android.versionCode and ios.buildNumber. A repeated build number is a common reason for a store to reject a build, so EAS can increment it for you: enable the remote version source and autoIncrement for the production profile. You change the user-facing version yourself before each release.

jsoneas.json
{  "cli": {    "appVersionSource": "remote"  },  "build": {    "production": {      "autoIncrement": true    }  }}

Android without Expo

  1. Create an upload key with keytool from the JDK and put my-upload-key.keystore in android/app.
  2. Set the file name, alias and passwords in ~/.gradle/gradle.properties.
  3. Add signingConfigs.release to android/app/build.gradle and reference it in buildTypes.release.
  4. Build the AAB: npx react-native build-android --mode=release. It runs the Gradle task bundleRelease under the hood, and the file appears at android/app/build/outputs/bundle/release/app-release.aab.
  5. Uninstall the previous version of the app from the phone and test the release build on it: npm run android -- --mode="release".
bashin the terminal
keytool -genkeypair -v -storetype PKCS12 \  -keystore my-upload-key.keystore \  -alias my-key-alias \  -keyalg RSA -keysize 2048 -validity 10000
properties~/.gradle/gradle.properties
MYAPP_UPLOAD_STORE_FILE=my-upload-key.keystoreMYAPP_UPLOAD_KEY_ALIAS=my-key-aliasMYAPP_UPLOAD_STORE_PASSWORD=change-meMYAPP_UPLOAD_KEY_PASSWORD=change-me
javaandroid/app/build.gradle
android {    signingConfigs {        release {            if (project.hasProperty('MYAPP_UPLOAD_STORE_FILE')) {                storeFile file(MYAPP_UPLOAD_STORE_FILE)                storePassword MYAPP_UPLOAD_STORE_PASSWORD                keyAlias MYAPP_UPLOAD_KEY_ALIAS                keyPassword MYAPP_UPLOAD_KEY_PASSWORD            }        }    }    buildTypes {        release {            signingConfig signingConfigs.release        }    }}
bashin the project directory
npx react-native build-android --mode=release

iOS without Expo

  1. In Xcode, open Product → Scheme → Edit Scheme, go to the Run tab and set Build Configuration to Release. Such a build disables the Dev Menu and embeds JavaScript in the app.
  2. Open the project’s .xcworkspace from the ios directory, select the “Any iOS Device (arm64)” destination and choose Product → Archive.
  3. In the archive window, click Distribute App → App Store Connect → Upload and choose automatic or manual signing management.
  4. The build appears in App Store Connect under TestFlight. Fill in the app details, select the build and click Submit For Review.

The Bundle Identifier in Xcode must match the identifier created in Apple Developer. To test a release build from the terminal, run npm run ios -- --mode="Release". Store requirements for signing, screenshots and review are covered in the “Android and Kotlin” reference, section “Signing and publishing to Google Play”, and the “iOS and Swift” reference, section “Signing and publishing to the App Store”. For builds in CI, see the CI/CD reference, section “Jobs, steps and matrices”.

Section sources

the section is written from these pages

Common errors and diagnostics

Start with the Metro output in the terminal and LogBox on the app screen: that is where JavaScript errors show up. If the native part fails to build, read the Gradle output or the Xcode build log. If the app can’t reach the development server, check the network and port 8081.

Order of checks

  1. Look at the development server output (npx expo start or npm start) and at LogBox on the device.
  2. Open React Native DevTools with the j key: while it is open, LogBox hides non-fatal errors, and the full list is in the console.
  3. If the native build fails, find the first error in the npm run android output or in the Xcode build log.
  4. If the device can’t connect, check that the computer and phone are on the same network and that port 8081 is free.

Port 8081 is already in use

Cause: the Metro development server runs on port 8081, and another process has taken it, for example a second running server.

bashon the computer
sudo lsof -i :8081
bashon the computer
# 12345 is the PID from the lsof outputkill -9 12345# or run Metro on a different portnpm start -- --port=8088

If you change the port, the app must load the bundle from the new port too: when running from Xcode, replace 8081 in the iOS project’s project.pbxproj file.

Error: spawnSync ./gradlew EACCES

Cause: the android/gradlew script doesn’t have the execute permission. The error appears on macOS when running npm run android.

bashin the project directory
ls -l android/gradlew
bashin the project directory
sudo chmod +x android/gradlew

Error "code":"ENOSPC","errno":"ENOSPC"

Cause: on Linux, Metro fails to start because the limit on directories that inotify can watch is exhausted. Watchman uses inotify.

bashon the computer
cat /proc/sys/fs/inotify/max_user_watches
bashon the computer
echo fs.inotify.max_user_watches=582222 \  | sudo tee -a /etc/sysctl.confsudo sysctl -p

com.android.ddmlib.ShellCommandUnresponsiveException

Cause: the ADB connection has hung, and installing the app on the device never completes. The build fails at the :app:installDebug task.

bashon the computer
adb devices
bashon the computer
adb kill-serveradb start-server

bridge configuration isn't available

Cause: the app on an Android phone connected over USB can’t reach the development server on the computer. In the adb devices output, the phone must be in the device state and only one device must be connected; unauthorized means USB debugging is not allowed on the phone.

bashon the computer
adb devices
bashon the computer
adb reverse tcp:8081 tcp:8081

Over Wi-Fi: connect the phone and computer to the same network, open the Dev Menu → Dev Settings → Debug server host & port for device and enter the computer’s IP address with the port, for example 192.0.2.10:8081. Then choose Reload JS.

Expo Go doesn’t open the project

Cause: the phone and computer are on different networks, a public network doesn’t let devices reach each other, or on an iPhone Expo CLI and Expo Go are signed in to different Expo accounts.

bashon the computer
npx expo login
bashin the project directory
npx expo start --tunnel

Sign in to Expo Go with the same account as in Expo CLI and scan the QR code again. A tunnel is slower than a local network, but it gets through the restrictions of public networks.

Nothing builds after upgrading React Native

Cause: an upgrade changes not only the versions in package.json but also the files of the native Android and iOS projects, and stale caches get in the way of the build.

bashin the project directory
npm ls react-native react
  • Without Expo, open Upgrade Helper, select the current and new versions and apply the changes to all files, not just package.json.
  • If the app still runs the old version, clear the project caches, for example with the react-native-clean-project utility.
  • In Expo, upgrade the SDK one version at a time: it is easier to find what broke. The react-native, react and expo versions change together.

Other problems

SymptomCauseWhat to do
npm WARN locking Error: EACCES when running the CLIno permissions on the npm directoriessudo chown -R $USER ~/.npm, and the same for /usr/local/lib/node_modules
No transports availablea module that uses WebSocket, such as Firebase, is loaded before react-nativeimport such modules after react-native
An iPhone can’t connect to the server over Wi-Fian open network with a captive portal doesn’t let devices reach each otherconnect the Mac and iPhone to a different network, for example a phone hotspot
Edits don’t appear on the phoneFast Refresh is turned offshake the phone and turn on Fast Refresh in the Dev Menu
Errors show only in DevTools, LogBox is emptywith DevTools open, LogBox hides non-fatal errorslook at the DevTools console

Section sources

the section is written from these pages

Versions and what’s new

This reference describes React Native 0.88 and Expo SDK 58. The latest release is 0.88.1 from 27 October 2026. A new minor branch ships on a schedule about every two months, and the three most recent are supported. The next branch is 0.89: the first candidate, 0.89.0-rc.0, is already in the next channel, and the stable release is expected on 7 December 2026.

BranchStatusReleasedLatest release
0.88 (described here)Active15 October 20260.88.1, 27 October 2026
0.87Active11 August 20260.87.1, 26 August 2026
0.86End of Cycle9 June 20260.86.3, 24 August 2026
0.85Unsupported7 April 20260.85.3, 5 May 2026

Active means frequent fixes. End of Cycle means fixes for serious regressions only; a final patch ships before the branch becomes Unsupported. Unsupported means no new releases, so upgrade as soon as possible. For production, use the npm latest channel; next carries release candidates and nightly carries daily builds. The documentation on reactnative.dev without a version number describes 0.88.

Expo SDK 58 was released on 15 October 2026 and includes React Native 0.88. The SDK jumps straight from 0.86, so it also contains the changes from 0.87.

What changed in 0.88 and Expo SDK 58

  • Core components: events now follow the W3C EventTarget model by default, as on the web, with a capture phase and bubbling. Event property names, event objects and call order are unchanged.
  • Core components: Text and TextInput support variable fonts through the fontVariationSettings style, as a string like in CSS or as an object such as { wght: 700 }.
  • Platform code: iOS now supports SceneDelegate. With the iOS 27 SDK, Apple requires the UIScene lifecycle, and UIKit apps built in Xcode 27 won’t launch without it. New projects are created with it; migrate existing ones with Upgrade Helper.
  • Platform code: Java Turbo Modules accept and return ArrayBuffer without converting to strings; Swift Package Manager support is improved but still experimental, and CocoaPods is fully supported.
  • Data: on Android, the default User-Agent header now contains the app name and version, as on iOS.
  • Installation and first run: Expo tooling requires Node.js 22.13 or later on the 22 line, 24.3 or later on the 24 line, or Node.js 26; odd-numbered lines are not supported. The npx expo start --tunnel tunnel no longer needs @expo/ngrok, but you must be signed in to an Expo account.
  • Build and publishing: in the Expo Android template, R8 is enabled for release by default (android.enableMinifyInReleaseBuilds=true); it shrinks and optimises Java and Kotlin code. Libraries that use reflection may need ProGuard rules.
  • Navigation: Expo Router has a rewritten navigation core. Most apps won’t notice; if you have a custom navigator or import from expo-router/react-navigation, check the migration guide.

0.88 ships React 19.3.0 and Metro 0.87. There are no breaking changes for apps, the third release in a row without any, after 0.83 and 0.86.

Deprecated and removed

APIStatusReplacement
react-native/Libraries/Core/InitializeCoredeprecated in 0.87react-native/setup-env
experimental_backgroundSize, experimental_backgroundPosition, experimental_backgroundRepeatdeprecated in 0.88the same names without the experimental_ prefix
InputAccessoryView (iOS)deprecated in 0.88KeyboardStickyView from react-native-keyboard-controller
InteractionManagerremoved in 0.87requestIdleCallback
The root export Touchable and the NativeMethods typesremoved in 0.87HostInstance instead of the types; for Touchable, extend ViewProps
Modal: the animated prop; StatusBar: backgroundColor, translucent, networkActivityIndicatorVisibleremoved in 0.87—
ImageBackgrounddeprecated in 0.87a View with an absolutely positioned Image
Deep imports from react-native/Libraries/*type error: the strict TypeScript API is the default since 0.87the public react-native API; temporarily disabling it through customConditions is planned for removal in 0.89
SafeAreaView from React NativedeprecatedSafeAreaView from react-native-safe-area-context
The old architecture (the bridge)not enabled since 0.82, classes are being removed graduallythe New Architecture, enabled by default

How to upgrade

  1. Without Expo, open Upgrade Helper, select your current version and the new one (0.88) and apply the changes to all files.
  2. With Expo, upgrade the SDK and the compatible package versions, then check the project with expo-doctor.
  3. If the android and ios directories were created by prebuild for the previous SDK, delete them: the next build will recreate them. If you edit them by hand, apply the changes using the Native project upgrade helper and run npx pod-install.
  4. Rebuild the development build.
bashin the Expo project directory
npx expo install expo@^58.0.0 --fixnpx expo-doctor@latest

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 3 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Manual edit

    reason: manual edit
  3. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

10 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “React Native” topic
All references · 61