React Native
React that builds real native views instead of DOM nodes: core components, Flexbox with different defaults, FlatList, navigation, the JS and UI threads, the New Architecture (JSI, Fabric, TurboModules), animations, and shipping with Expo.
The 30-second version
You already know how to build a screen with ReactReactA JavaScript library for building user interfaces from components: you describe what the UI should look like for the current data, and React updates the DOM to match.: components, PropsPropsThe inputs a React component receives from its parent, like arguments to a function. A component shouldn't change its own props., stateState (React)Data a component remembers between renders, like the text in a search box. Changing it with its setter makes React render that component again., hooksHook (React)A function whose name starts with use (useState, useEffect, useMemo…) that lets a component keep state or run side effects. Hooks must be called in the same order on every render.. React Native lets you use exactly that to build an iPhone or Android app. A common first guess is that it wraps a website inside an app. It does not.
Three words first. A native viewNative viewA user-interface object made by the phone's own toolkit: a UIView on iOS, an android.view.View on Android. The system's own apps (Settings, Messages) are built from the same objects. is a user-interface object made by the phone's own toolkit: a UIView on iOS, an android.view.View on Android. A rendererRenderer (React)The part of React that turns the tree your components describe into something real. react-dom creates DOM nodes in a browser; React Native's renderer creates native views on a phone. Your components and hooks are the same for both. is the part of React that turns the tree your components describe into something real. On the web that part is react-dom, and "real" means DOMDOMThe Document Object Model: the browser's tree of objects that represents the page. Every button, input and div is a DOM node you can attach event listeners to. nodes. A WebViewWebViewA native view that contains a small browser. An app can show a web page inside it. “Hybrid” apps (Cordova, Capacitor) are one WebView that fills the screen and runs an ordinary website. is a native view with a small browser inside it.
Switch between the four and watch the right-hand side:
<View>
<Text>Likes: 3</Text>
<Pressable onPress={like}>
<Text>♥ Like</Text>
</Pressable>
</View>UIView objects, the same building blocks Apple's own apps use. There is no browser and no DOM.In React Native 0.88 you can find those classes in the package itself: a <View> is backed by RCTViewComponentView, which is a UIView, on iOS, and by ReactViewGroup, which is an android.view.ViewGroup, on Android.
This one design decision explains most of what's different from the web:
No DOM, no CSS files
divs and no stylesheets. You compose a small set of native components and style them with JavaScript objects (§02–§04).Two worlds, two threads
An app, not a page
Coming from the web: what carries over
What stays the same
React Native uses the real react package (19.3 with React Native 0.88). So all of this is unchanged:
- Components are functions that return JSXJSXHTML-like syntax inside JavaScript (<Button onClick={save}>Save</Button>) that a build tool turns into ordinary function calls creating React elements.. Props go down, events come up.
useState,useEffect,useRef,useMemo, contextContext (React)A way to pass a value to every component below a Provider without threading it through props at each level. Components read it with useContext (or use() in React 19) and re-render when it changes. In React 19 you can write <MyContext value={…}> instead of <MyContext.Provider value={…}>. and custom hooksCustom hookYour own function whose name starts with use and that calls other hooks inside. It shares stateful logic (not state itself): each component that calls it gets its own copy of the state. behave exactly as React Hooks, Honestly describes, stale closuresStale closureA function that was created during an old render and still reads that render's values, even though the component has since re-rendered with newer ones. The classic symptom: an interval that always sees 0. included.- Keyskey (React)A special prop (key="…") that tells React which item is which in a list, so it can match old and new items by identity instead of by position. It is not passed to your component., re-rendering and
memoReact.memoA wrapper (memo(Component)) that makes React skip re-rendering that component when its parent re-renders, as long as every prop is the same value (Object.is) as last time. follow the rules in How React Works. - Your state libraries work too: anything from State Management that doesn't touch the DOM runs as it is.
What changes
There is no browser, so nothing that the browser provided exists: no document, no window.location, no <div>, no CSS files, no localStorage. In their place you get a small set of core componentsCore componentA component that ships with React Native and maps to a native view: View, Text, Image, TextInput, ScrollView, Pressable, FlatList and a few more. They play the role that HTML tags play on the web., imported from react-native. Each one is backed by a native view.
| On the web | In React Native | Notes |
|---|---|---|
<div> | <View> | A box. Lays out its children with Flexbox (§04). Can't contain a bare string. |
<p>, <span>, <h1> | <Text> | The only component that can draw characters. |
<button>, anything with onClick | <Pressable onPress> | A touchable area. You draw what's inside it. |
<input>, <textarea> | <TextInput> | onChangeText gives you the new string directly. |
<img> | <Image source> | A remote image needs an explicit width and height. |
a div with overflow: auto | <ScrollView> | Views don't scroll on their own. Scrolling is a component you opt in to. |
| a long list | <FlatList> | Renders only the rows near the screen (§05). |
Here is the same component on both sides. Switch tabs and compare line by line:
import { useState } from "react";
import { Pressable, Text, View } from "react-native";
export default function LikeButton() {
const [likes, setLikes] = useState(0); // the same hook as on the web
return (
<View style={{ padding: 16 }}>
<Text style={{ fontSize: 18 }}>Likes: {likes}</Text>
<Pressable onPress={() => setLikes((n) => n + 1)}>
<Text>♥ Like</Text>
</Pressable>
</View>
);
}Three differences matter most in your first hour. (The web tab is ordinary react-dom code, shown only for comparison.)
1. Every string lives inside <Text>. A View is a plain box; drawing letters is Text's job. If a string ends up directly inside a View, a development build of React Native 0.88 logs the error Text strings must be rendered within a <Text> component. and shows it in the app. Treat it as a bug to fix on the spot: the production renderer doesn't include that check, so a release build gives you no message at all. The classic way to hit it is {count && <Badge />} when count is 0: React renders the 0, and a bare 0 inside a View is text outside <Text>. Write {count > 0 && <Badge />}.
2. onPress, not onClick. There is no mouse. Pressable also gives you onLongPress, onPressIn and onPressOut, and it has no built-in look: no border, no background, no cursor. What the user sees is whatever you put inside.
3. style takes an object, never a string, and there is no className. The next section is about that.
A slightly bigger example
A profile form uses most of the core components:
import { useState } from "react";
import { Image, Pressable, ScrollView, Text, TextInput } from "react-native";
export default function ProfileForm() {
const [name, setName] = useState("");
return (
<ScrollView keyboardShouldPersistTaps="handled">
<Image
source={{ uri: "https://example.com/avatar.png" }}
style={{ width: 96, height: 96, borderRadius: 48 }} // ← a remote image needs a size
/>
<TextInput
value={name}
onChangeText={setName} // ← hands you the string, not an event
placeholder="Your name"
autoCapitalize="words"
/>
<Pressable
onPress={() => console.log("saved", name)}
style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}
>
<Text>Save</Text>
</Pressable>
<Text>
Hello, <Text style={{ fontWeight: "bold" }}>{name || "stranger"}</Text>
</Text>
</ScrollView>
);
}keyboardShouldPersistTaps="handled" is a mobile-only concern. When the on-screen keyboard is open, the first tap outside the input normally just closes the keyboard. With "handled", a tap on the Save button counts as a tap on the button.
Try it yourself
The quickest way to run this code is ExpoExpoA framework and set of tools on top of React Native: a project template, a CLI, a file-based router, about a hundred maintained native modules, and cloud services for building and updating apps., the framework most React Native projects start from (§10 covers what it is and when you'd leave its defaults):
npx create-expo-app@latest my-app # create-expo-app 5.0, default template for SDK 58
cd my-app
npx expo start # starts the dev server and prints a QR codeThe dev serverDev server (React Native)The program on your computer, started by npx expo start, that bundles your JavaScript and sends it to the app on your phone or simulator while you develop. It pushes changes when you save a file. is a program on your computer that sends your JavaScript to the app while you develop. To see the app, you have two choices:
- On your own phone: install the free Expo GoExpo GoA ready-made app from the app stores that can load your JavaScript from your computer. Good for learning, but it only contains the native modules Expo chose to include. app from the App Store or Google Play and scan the QR code with it (on an iPhone, with the Camera app). Phone and computer must be on the same Wi-Fi. §10 explains Expo Go's limits.
- On your computer: press
iin that terminal for the iOS Simulator (needs a Mac with Xcode installed) orafor the Android emulator (needs Android Studio).
The generated project (template version 58.0.32) has TypeScript, a router and two example screens in src/app/. Edit src/app/index.tsx, save, and the running app updates in about a second while keeping its state. That's Fast RefreshFast RefreshReact Native's hot reloading: when you save a file, the running app swaps in the changed components within a second or so and keeps their state., the mobile cousin of HMRHot module replacement (HMR)When you save a file, the dev server sends the browser just that changed module and swaps it into the running page without a full reload, so the app keeps its state (open dialogs, typed text, React state).. A simulatorSimulator / emulatorA program on your computer that behaves like a phone: the iOS Simulator (Mac only) and the Android Emulator. Faster to iterate on than a real device, but performance and sensors differ. is quicker to work with; a real phone tells you the truth about speed and touch.
Styling: objects, no cascade, and a new kind of pixel
StyleSheet
You could write every style inline, as §02 did. For anything longer, declare the objects once with StyleSheetStyleSheetReact Native's object for declaring styles in JavaScript. StyleSheet.create({ card: { padding: 16 } }) returns the same object, checked by TypeScript, and you pass styles.card to a component's style prop.:
import { StyleSheet, Text, View } from "react-native";
export function Card({ title, urgent }: { title: string; urgent: boolean }) {
return (
<View style={[styles.card, urgent && styles.urgent]}>
<Text style={styles.title}>
{title} <Text style={styles.badge}>new</Text>
</Text>
</View>
);
}
const styles = StyleSheet.create({
card: {
padding: 16, // a plain number: density-independent pixels
borderRadius: 12,
backgroundColor: "#1e293b",
},
urgent: { borderWidth: 2, borderColor: "tomato" },
title: { color: "white", fontSize: 18 },
badge: { fontSize: 12 }, // still white: text style passes from <Text> to nested <Text>
});No cascade, almost no inheritance
On the web, color: white on a card makes every text inside it white. That's the cascadeCascade (CSS)The CSS rules that decide which declaration wins when several selectors match one element, plus inheritance from parent to child. React Native has neither: a component gets exactly the styles in its own style prop. and inheritance at work. React Native has neither:
- A
View's style affects that view only. You can't even putcoloron aView: TypeScript rejects it, because a box has no text to colour. - There are no selectors, so no
.card p, no:hover, no!important, and no specificity to fight. - The one exception: a
<Text>nested inside a<Text>inherits the outer one's text styles. That is why the "new" badge above is white without saying so.
So how do you make all body text grey? With a component. You write <AppText> once, give it the default style, and use it everywhere instead of Text. In React Native, components do the job that CSS classes do on the web. The same goes for themes: a colour palette is a JavaScript object you import, or put in contextContext (React)A way to pass a value to every component below a Provider without threading it through props at each level. Components read it with useContext (or use() in React 19) and re-render when it changes. In React 19 you can write <MyContext value={…}> instead of <MyContext.Provider value={…}>. if it can change (useColorScheme() from react-native tells you whether the phone is in dark mode).
Density-independent pixels
Phone screens differ a lot in how many physical dots they pack into a centimetre. If width: 100 meant 100 physical pixels, a button would be finger-sized on one phone and tiny on another.
React Native's unit is the density-independent pixelDensity-independent pixel (dp)React Native's length unit. One dp is about the same physical size on every phone: a screen with 3 times more dots per inch uses 3 × 3 physical pixels for it. iOS calls the unit a point, Android calls it dp. (dp; iOS calls it a point). One dp is roughly the same physical size on every device. The system multiplies by the screen's scale factor to get physical pixels:
If you know CSS pixelsCSS pixel (px)CSS's basic length unit. It's not one physical screen dot: on a high-density phone screen one CSS pixel may be 2–3 device pixels, so 16px text looks about the same size everywhere., this is the same idea. What's missing is every other CSS unit:
| You want | You write | Not understood |
|---|---|---|
| a fixed size | width: 120 (a number, no unit) | "120px", "2rem", "1em" |
| a share of the parent | width: "50%" | "50vw", "calc(100% - 16px)" |
| a share of the screen | const { width } = useWindowDimensions() then arithmetic | media queries in a stylesheet |
| "fill what's left" | flex: 1 (§04) |
Be careful with the right-hand column: TypeScript won't stop you. A size is typed as number | string in 0.88, so width: "120px" compiles. At runtime the layout code only understands a number, a percentage and a few keywords such as "auto", and it ignores anything else.
fontSize is a special case. The user's text-size setting in the system scales it, so fontSize: 16 can end up larger on a phone set to large text. That's an accessibility feature. Leave room for text to grow, and don't hard-code the height of a box that holds text.
One codebase, two platforms
Most styles are identical on iOS and Android. For the rest, Platform tells you where you are:
import { PixelRatio, Platform, StyleSheet, Text, useWindowDimensions } from "react-native";
export function DeviceInfo() {
const { width, height } = useWindowDimensions(); // re-renders when the phone rotates
return (
<Text style={styles.mono}>
{Platform.OS}: {width} × {height} dp, {PixelRatio.get()} physical pixels per dp
</Text>
);
}
const styles = StyleSheet.create({
mono: {
fontFamily: Platform.select({ ios: "Menlo", default: "monospace" }),
paddingTop: Platform.OS === "android" ? 8 : 0,
},
});On a phone, Platform.OS is "ios" or "android". (React Native also runs on the web, Windows and macOS through separate projects, with their own values.) Platform.select picks the value for the current platform and falls back to default. When a whole component differs, split the file: next to Map.tsx you can have Map.ios.tsx and Map.android.tsx, and the bundlerBundlerA build tool (Vite/Rollup, esbuild, webpack) that follows your imports and combines your modules and libraries into a few optimized files for the browser. picks the right one for each build. Your imports still say ./Map.
Layout: Flexbox with different defaults
View is already a flex container. The rules are the ones you know from CSS, with three defaults changed.On the web you pick a layout mode per element: normal flow, flex, grid. React Native ships a single layout engine, YogaYogaThe C++ layout engine inside React Native. It takes each view's flexbox styles and computes its position and size. It implements Flexbox (not CSS Grid or floats), with React Native's own defaults., and Yoga implements FlexboxFlexboxA CSS layout mode for arranging items in one direction (a row or a column), sharing space and aligning them.. There is no display: block and there are no floats. CSS Grid isn't available either: in 0.88 the display style accepts only "flex", "none" and "contents". A flex container lines its children up along one direction, the main axis. justifyContent positions them along that axis, and alignItems positions them across it (the cross axis). If that's new to you, CSS Layout §04 has the long explanation and a playground.
The three defaults that differ
These come straight from Yoga's source in React Native 0.88 (ReactCommon/yoga/yoga/style/Style.h):
| Property | React Native default | CSS default (inside display: flex) | What you notice |
|---|---|---|---|
flexDirection | column | row | Children stack top to bottom unless you ask for a row. |
flexShrink | 0 | 1 | Children that don't fit are cut off instead of squeezed. |
alignContent | flex-start | stretch | Only matters with flexWrap: wrapped lines pack at the start. |
Everything else matches the web: alignItems defaults to stretch, justifyContent to flex-start, and flexWrap to no wrapping. Two more defaults are worth knowing. Sizes use box-sizing: border-box, so width includes padding and border (the setting CSS Layout §02 recommends). And position defaults to relative, so position: "absolute" on a child is measured from its parent without any extra setup.
flex: 1 also reads a little differently. In React Native, flex takes one number. flex: 1 means "grow to fill the free space, and shrink if needed". It's what you put on the part of a screen that should take whatever is left.
Play with it. Start by flipping defaults back and forth without touching anything else:
<View style={{ flex: 1 }}>
<Box>A</Box>
<Box>Bee</Box>
<Box>A long label that needs room</Box>
</View>flexDirection is column: children stack top to bottom. Each one stretches across the full width, because alignItems defaults to stretch (the same as on the web).A whole screen
The most common layout in any app is a fixed header, a body that fills the rest, and a fixed footer:
import { StyleSheet, Text, View } from "react-native";
export default function InboxScreen() {
return (
<View style={styles.screen}>
<View style={styles.header}>
<Text>Inbox</Text>
<Text>Edit</Text>
</View>
<View style={styles.body}>
<Text>Messages go here</Text>
</View>
<View style={styles.footer}>
<Text>3 unread</Text>
</View>
</View>
);
}
const styles = StyleSheet.create({
screen: { flex: 1 }, // fill the parent; children stack in a column
header: {
flexDirection: "row", // ← opt in to a row
justifyContent: "space-between",
alignItems: "center",
height: 56,
paddingHorizontal: 16,
},
body: { flex: 1, padding: 16, gap: 12 }, // takes all the height that is left
footer: { height: 48, alignItems: "center", justifyContent: "center" },
});Work through the numbers on a screen that is 800 dp tall. The header takes 56 and the footer 48. That leaves 800 − 56 − 48 = 696 dp of free space, and the body is the only child with flex: 1, so it gets all 696.
Break the chain yourself:
<View style={{ flex: 1 }}>
<View style={{ flex: 1 }}>
<FlatList style={{ flex: 1 }} data={messages} renderItem={renderRow} />
</View>
</View>flex: 1 passes that height one level down, so the list has 800 dp to fill.The notch, the status bar and the home indicator
A web page gets a clean rectangle from the browser. An app gets the whole glass, including the parts covered by the camera cutout, the rounded corners, the status bar (clock, battery) and the bar at the bottom that you swipe to go home. The part that's safe to put content in is the safe areaSafe areaThe part of the screen that isn't covered by the notch, the camera cutout, rounded corners, the status bar or the home indicator. Content outside it can be hidden or hard to tap., and the distances from each edge are its insetsInsetHow far the safe area starts from one edge of the screen, in dp. A phone with a notch might report a top inset of 59 and a bottom inset of 34.. Flip the safe area switch in the playground above to see box A slide under the cutout.
The values differ per device and change when the phone rotates, so you ask for them:
import { Text, View } from "react-native";
import { SafeAreaProvider, useSafeAreaInsets } from "react-native-safe-area-context";
export default function App() {
return (
<SafeAreaProvider>
<Home />
</SafeAreaProvider>
);
}
function Home() {
const insets = useSafeAreaInsets(); // for example { top: 59, bottom: 34, left: 0, right: 0 }
return (
<View style={{ flex: 1, paddingTop: insets.top, paddingBottom: insets.bottom }}>
<Text>Never hidden by the notch or the home bar</Text>
</View>
);
}SafeAreaProvider goes once near the root of the app. Then any component can call useSafeAreaInsets(), or you can use the library's <SafeAreaView>, which is a View that applies the padding for you. (The example numbers are typical for a recent iPhone; yours will differ.)
What you can't do
- No Grid (as of 0.88). Yoga's source code has started to grow a grid mode, but styles can't select it yet. Build grids from rows and columns of Views, with
flexWrap: "wrap"and percentage widths, or useFlatList'snumColumnsprop for a list of cards. - No media queries. Read the size with
useWindowDimensions()(§03) and choose styles in JavaScript. The hook re-renders your component on rotation. - Nothing scrolls by itself. Content taller than the screen is clipped. Wrap it in a
ScrollView, or use aFlatListfor long lists, which is next.
Lists: FlatList and the render window
ScrollView creates every child up front. A FlatList creates only the rows near the screen, and swaps them as you scroll. For anything longer than a couple of screens, use FlatList.The problem
This is the obvious way to show an inbox, and it's fine for 20 messages:
import { ScrollView, Text } from "react-native";
type Message = { id: string; text: string };
export function Inbox({ messages }: { messages: Message[] }) {
return (
<ScrollView>
{messages.map((m) => (
<Text key={m.id}>{m.text}</Text> // 5,000 messages → 5,000 native views, right now
))}
</ScrollView>
);
}With 5,000 messages, React must render 5,000 components, and React Native must create, measure and keep 5,000 native views before the first frame appears. The user sees eight of them. Startup is slow, and memory is spent on rows nobody will scroll to.
The fix: only mount a window
A component is mountedMount / unmountMount: a component appears on the page for the first time and React creates its state. Unmount: it is removed, and its state and effects are thrown away. while it exists on the screen with its state, and unmounted when React removes it. The idea is list virtualizationList virtualization (windowing)Rendering only the rows of a long list that are currently visible (plus a few extra), and swapping them as the user scrolls, so 10,000 items cost about as much as 20., the same one the web uses for huge tables. FlatList keeps a render windowRender window (FlatList)The slice of a list that FlatList keeps mounted: the visible rows plus a margin above and below. Rows outside it are unmounted and replaced by empty space of the same height. mounted: the rows on screen plus a margin above and below. Everything outside the window is replaced by empty space of the right height, so the scrollbar still behaves as if all rows were there.
Try both components, then fling:
windowSize={21}). Everything else is empty space of the right height.The widget is a simplified model, but its numbers are React Native 0.88's real defaults:
| Prop | Default | Meaning |
|---|---|---|
initialNumToRender | 10 | Rows rendered in the very first pass. |
windowSize | 21 | Size of the window, measured in screens: the visible one plus 10 above and 10 below. |
maxToRenderPerBatch | 10 | At most this many new rows per batch. |
updateCellsBatchingPeriod | 50 ms | Wait between batches. |
Rows are rendered in small batches on purpose. One batch is a short piece of JavaScript work, so taps and other events get a turn in between. The price shows when you fling: the list moves by itself on the native side, the batches can't keep up, and you see blank cellsBlank cellsEmpty space you see in a virtualized list when you scroll faster than new rows can be rendered. The space is reserved, the rows just haven't been created yet. for a moment. Those are reserved space whose rows haven't been rendered yet. Nothing is broken, but it looks cheap, and the rest of this section is about making it rare.
Writing it
import { memo } from "react";
import { FlatList, StyleSheet, Text, View } from "react-native";
type Message = { id: string; text: string };
const ROW_HEIGHT = 64;
const Row = memo(function Row({ text }: { text: string }) {
return (
<View style={styles.row}>
<Text numberOfLines={1}>{text}</Text>
</View>
);
});
export function Inbox({ messages }: { messages: Message[] }) {
return (
<FlatList
data={messages}
keyExtractor={(m) => m.id} // a stable id, not the index
renderItem={({ item }) => <Row text={item.text} />}
getItemLayout={(_data, index) => ({ // only when every row has the same height
length: ROW_HEIGHT,
offset: ROW_HEIGHT * index,
index,
})}
/>
);
}
const styles = StyleSheet.create({
row: { height: ROW_HEIGHT, justifyContent: "center", paddingHorizontal: 16 },
});You hand over the data and a function that renders one row. FlatList decides which rows to call it for. Four details matter:
keyExtractorreturns each row's keykey (React)A special prop (key="…") that tells React which item is which in a list, so it can match old and new items by identity instead of by position. It is not passed to your component.. Use a real id. With the array index as key, deleting the first message makes React think every row changed its content, as How React Works shows.renderItemreceives an object;{ item }pulls the message out of it. Keep the row a separate component wrapped inmemoReact.memoA wrapper (memo(Component)) that makes React skip re-rendering that component when its parent re-renders, as long as every prop is the same value (Object.is) as last time., so rows whose props didn't change are skipped when the list re-renders.getItemLayouttells FlatList where every row is without measuring it. For row 300 with 64 dp rows:offset = 64 × 300 = 19,200. Without it, FlatList has to render rows to learn their heights, so it can't jump straight to a far-away position, andscrollToIndexon an unmeasured row fails. Only provide it when your rows really are a fixed height.numberOfLines={1}cuts long text with "…", which is what keeps the height fixed.
When rows are still blank
Work down this list:
- Make rows cheaper. A row that renders three nested components with images costs many times more than a text line. Heavy rows are the most common cause.
- Stop unneeded re-renders. Put
memoon the row, and keep per-row state inside the row. Also keeprenderItemandkeyExtractorstable, meaning the same function object from one render to the next. The example above writes them inline, which creates new functions on every render ofInbox. A project made from the Expo SDK 58 template has the React CompilerReact CompilerA build-time tool (babel-plugin-react-compiler) that rewrites your components to cache values and elements automatically, so you need far fewer manual memo / useMemo / useCallback calls. switched on, and it caches such functions for you. Without the compiler, move them outside the component or wrap them inuseCallback. The memo section of How React Works explains how to measure the effect. - Give
getItemLayoutwhen heights are fixed. - Then tune, measuring each change on a slow Android phone: a smaller
windowSizesaves memory but shows blanks sooner; a largermaxToRenderPerBatchfills faster but makes each batch block taps for longer.
How it runs: Hermes, the JS thread and the UI thread
Where your JavaScript runs
There's no browser, so something else has to execute your code. That is a JavaScript engineJavaScript engineThe program that runs JavaScript. Chrome and Node.js use V8, Safari uses JavaScriptCore, and React Native uses Hermes. embedded in the app, and in React Native it's HermesHermesThe JavaScript engine React Native ships with. It is built for phones: your code is compiled to bytecode on your build machine, so the app doesn't have to parse JavaScript at startup., an engine built for phones. (Chrome and Node.js use an engine called V8. Hermes is a different one with different trade-offs; §11 explains what it's optimized for.)
Hermes runs your whole app on a single threadThreadOne worker that runs your code line by line. A program can have several threads, and the operating system decides which one runs on which CPU core., the JS threadJS threadThe one thread on which Hermes runs all your JavaScript: components, hooks, event handlers, timers, your whole app logic. While it is busy, no other JavaScript can run.. Components, hooks, event handlers, timers, fetch callbacks, your state library: all of it takes turns on that one thread, with the same event loop model as in a browser. The Event Loop explains that model; nothing about it changes here.
The native views are somewhere else. iOS and Android both insist that views are created and changed on one particular thread, the app's main thread. React Native calls it the UI threadUI thread (main thread)The app's main thread, owned by iOS or Android. Only this thread may create and change native views, and it receives touches. If it stalls, the whole app looks frozen.. It also receives touches and draws each frameFrameOne complete picture shown on the screen. Smooth motion is many frames per second, each slightly different, like the pages of a flip book..
One tap, step by step
Here is the Like button from §02. Step through what happens between your finger touching the glass and the number changing:
1import { useState } from "react";2import { Pressable, Text, View } from "react-native";34export default function LikeButton() {5 const [likes, setLikes] = useState(0);6 return (7 <View style={{ padding: 16 }}>8 <Text style={{ fontSize: 18 }}>Likes: {likes}</Text>9 <Pressable onPress={() => setLikes((n) => n + 1)}>10 <Text>♥ Like</Text>11 </Pressable>12 </View>13 );14}
Four names from that walkthrough come back later:
- Render is React calling your components on the JS thread. It's the same phase described in How React Works.
- The shadow treeShadow treeFabric's own copy of your UI tree, kept in C++: one node per native view, holding its props and its computed position and size. It is what layout runs on, before any real view is touched. is the renderer's own copy of the UI, kept in C++. Layout (Yoga, §04) runs on it. No native view is involved yet.
- Commit is the step after render: the new shadow tree is laid out and becomes the next tree to show. (React's own commit phase is where this is triggered.)
- MountMount phase (Fabric)The last step of a React Native update: the UI thread applies a list of changes (create this view, update that text, move this one) to the real native views. is the UI thread applying the resulting changes to real native views. Careful with this word: §05 and §06 used React's meaning of "mounted" (a component exists and has state). The renderer reuses it for this last step.
There are other threads too. Network requests, image decoding and storage run on background threads owned by native code, so a slow download never blocks either of the two above. You don't manage those threads; you see them as promises that resolve later.
What a busy JS thread does to the app
Every handler needs the JS thread, so it matters what happens while that thread is busy. Suppose a press handler sorts a big array for three seconds:
import { useState } from "react";
import { ActivityIndicator, Pressable, ScrollView, Text } from "react-native";
function slowSort(items: number[]): number[] {
const end = Date.now() + 3000;
while (Date.now() < end) {} // stand-in for 3 s of real work on the JS thread
return [...items].sort((a, b) => a - b);
}
export default function Report({ numbers }: { numbers: number[] }) {
const [sorted, setSorted] = useState<number[]>([]);
const [taps, setTaps] = useState(0);
return (
<ScrollView>
<ActivityIndicator />
<Pressable onPress={() => setSorted(slowSort(numbers))}>
<Text>Sort {numbers.length} numbers</Text>
</Pressable>
<Pressable onPress={() => setTaps((n) => n + 1)}>
<Text>Tapped {taps} times</Text>
</Pressable>
<Text>{sorted.slice(0, 100).join(", ")}</Text>
</ScrollView>
);
}Predict what the user can still do during those three seconds, then try it in this simulation:
The split is always the same:
| Keeps working (UI thread) | Waits (needs the JS thread) |
|---|---|
Scrolling a ScrollView or FlatList that is already rendered | Any onPress, onChangeText, onScroll handler |
| The native spinner, the keyboard, system gestures | State updates and re-renders |
On Android, a Pressable's android_ripple effect, which Android draws itself | A Pressable's pressed style from §02 (it is JavaScript state) |
| Animations that were handed to the UI thread (§09) | Timers, fetch callbacks, navigation started from JavaScript |
| New FlatList rows (they are rendered by JavaScript, so you get blank cells) |
Compare this with a web page. There, JavaScript and rendering share the browser's main thread, so a long task freezes everything, scrolling often included. A React Native app with a blocked JS thread looks alive (it scrolls, it spins) but doesn't react. Users describe it as "the buttons don't work".
Keeping the JS thread free
At 60 frames per secondFrame rate (fps) / refresh rateFrame rate: how many new pictures the page produces per second. Refresh rate: how many times per second the screen can show a new one (60 Hz is common; many phones and laptops do 120 Hz). a frame lasts about 16.7 ms, and at 120 it's about 8.3 ms. Any single piece of JavaScript that runs much longer than that delays whatever is queued behind it. The cures are the web's cures:
- Do less per event. Render fewer components (§05), avoid re-rendering the whole screen for a small change (why components re-render).
- Split long work into chunks that yield between them, so events get a turn.
requestIdleCallbackexists in React Native 0.88 for work that can wait for a quiet moment. - Move heavy computing off the JS thread: to your server, or into native code (§10).
- Mark non-urgent updates as transitions (
useTransition,useDeferredValue), which work here as on the web. See React Hooks §12.
The old bridge and the New Architecture
You can build apps without knowing this section. Read it anyway if you maintain an older app, pick libraries, or wonder why articles from a few years ago describe problems you never see.
The bridge
§07 showed two worlds: Hermes on the JS thread, native views and native modulesNative moduleA piece of Kotlin, Swift, Objective-C or C++ code that JavaScript can call, used to reach platform features with no JavaScript API: the camera, Bluetooth, the keychain, a payment SDK. on the other side. Until recently they had exactly one way to talk, the bridgeThe bridgeThe original way JavaScript and native code talked in React Native: messages were turned into JSON-like text, queued, and sent in batches to the other side, always asynchronously. Replaced by JSI.:
- A call was serializedSerializeTurn a value in memory (an object, an array) into a flat sequence of text or bytes so it can be sent somewhere else, where it is parsed back into a value. JSON.stringify is serialization.: turned into a small JSONJSONJavaScript Object Notation: a text format for data, like {"id": 7, "tags": ["a"]}. Readable by humans and every language; the default body format for web APIs.-like message such as "module 12, method 0, these arguments".
- Messages were collected in a queue and sent across in batches.
- The other side decoded each message and made the real call.
- Any result travelled back the same way.
Step through one native call on each architecture:
1// Old architecture (the default before 0.76)2import { NativeModules } from "react-native";34NativeModules.Battery.getLevel((level) => {5 console.log(level);6});7console.log("asked");
NativeModules.Battery isn't the native object. It's a JavaScript stand-in whose only job is to write a message.The bridge had three costs that shaped how React Native apps were written:
- Calls were asynchronous by default. JavaScript normally couldn't ask native code a question and use the answer on the next line. Measuring a view's size, for example, took a round trip, and the answer could arrive a frame late. (A blocking, synchronous kind of method did exist. The macro is still in the 0.88 iOS sources with a warning that calling methods synchronously "can have strong performance penalties" and a note that it is "not supported" under the old remote debugger, so libraries avoided it.)
- Data was copied. A big list of rows or an image encoded as text was serialized on one side and parsed on the other.
- Modules were loaded up front. By default all native modules were set up at startup, whether the first screen used them or not.
JSI: the piece that removed it
JSIJSI (JavaScript Interface)A C++ API through which native code can put objects and functions directly into the JavaScript engine. JavaScript then calls native code like an ordinary function, with no message queue in between. (JavaScript Interface) is a small C++ API for a JavaScript engine. With it, native code can create a host objectHost objectAn object that looks like a normal JavaScript object but is implemented in C++. Reading a property or calling a method on it runs native code immediately.: something that JavaScript sees as an ordinary object, but whose property reads and method calls run C++ immediately, with no message, queue or serialization in between. A call can return its value synchronously, and both sides can hold references to each other's objects.
Everything else in the New ArchitectureNew ArchitectureThe rewrite of React Native's internals: JSI instead of the bridge, the Fabric renderer, TurboModules and Codegen. Default since 0.76, and the only option since 0.82. is built on that:
| Piece | Replaces | What it is |
|---|---|---|
| JSI | the bridge | Direct calls between JavaScript and C++. |
| FabricFabricThe New Architecture's renderer. Its core is written in C++ and shared by iOS and Android: it keeps the shadow tree, asks Yoga for layout, and tells the UI thread which native views to create or change. | the old renderer | The renderer from §07. Its core is C++, shared by iOS and Android. It keeps the shadow tree, runs Yoga, and can measure and update views synchronously when it must. It's also what lets React 18+ features such as transitions and Suspense work properly on native. |
| TurboModulesTurboModuleA native module in the New Architecture. It is loaded only when first used, its methods are called through JSI, and its JavaScript-to-native types are checked by generated code. | bridge-based native modules | Native modules called through JSI and created lazily, on first use. |
| CodegenSpec (Codegen)A TypeScript file that declares a native module's methods and their types. React Native's Codegen reads it at build time and generates the C++, Kotlin and Objective-C glue, so both sides agree on the types. | hand-written glue | Generates the typed C++/Kotlin/Objective-C glue between the two sides from a TypeScript spec. |
A TurboModule from the JavaScript side
You'll rarely write one in your first year, but reading one demystifies the libraries you install. The contract is an ordinary TypeScript file, a specSpec (Codegen)A TypeScript file that declares a native module's methods and their types. React Native's Codegen reads it at build time and generates the C++, Kotlin and Objective-C glue, so both sides agree on the types.:
import type { TurboModule } from "react-native";
import { TurboModuleRegistry } from "react-native";
export interface Spec extends TurboModule {
getLevel(): number; // synchronous: returns in the same call
waitUntilCharged(target: number): Promise<void>; // asynchronous: native resolves it later
}
export default TurboModuleRegistry.getEnforcing<Spec>("NativeBattery");At build time, React Native's Codegen (a code generator: a tool that writes source code from a description) reads this file (your package.json points to it under a codegenConfig key) and generates the native interfaces. The implementations, written in Kotlin for Android and Swift or Objective-C for iOSKotlin, Swift, Objective-CThe languages native apps are normally written in: Kotlin (and older Java) on Android, Swift (and older Objective-C) on iOS. React Native's own internals also use C++, which both platforms can run., must then match those interfaces, or the app doesn't compile. On the bridge, a mismatch such as JavaScript sending a string where native expected a number only showed up as a crash at runtime.
Using the module looks like calling any function:
import { Text } from "react-native";
import NativeBattery from "./specs/NativeBattery";
export function BatteryBadge() {
const level = NativeBattery.getLevel(); // a direct call into native code, no await
return <Text>{Math.round(level * 100)}%</Text>;
}A synchronous native call runs on the JS thread and blocks it until it returns, so it's only appropriate for fast lookups. Anything slow (disk, network, a sensor that needs to warm up) should return a Promise, as waitUntilCharged does.
Where things stand in React Native 0.88
As of 0.88:
- 0.76 was the first release whose new-project template turned the New Architecture on (
newArchEnabled=true; 0.75's template hadfalse). - 0.82 removed the choice. The 0.88 build scripts say so in as many words: setting
newArchEnabled=falseon Android orRCT_NEW_ARCH_ENABLED=0on iOS "is not supported anymore since React Native 0.82", and the app runs with the New Architecture regardless. - Hermes is the engine. The 0.88 iOS build script's comment reads "use Hermes is the default. The only other option is the third-party JSC": JavaScriptCore, the engine early React Native used, is no longer part of core.
- Classes of the old architecture still ship in the Android sources, marked
@LegacyArchitecturewith the note that they "will be removed in a future release". The JavaScript side still hasNativeModulesand an interop layerInterop layerCompatibility code that lets a library written for the old architecture keep working on the new one, by wrapping its old-style native module or view., so many older libraries keep working without changes.
Animations and gestures: stay on the UI thread
The tempting way, and why it stutters
You know one way to change the screen: setState. So the obvious way to slide a card is to call setX(x + 4) many times a second. Each of those is a full trip from §07: JS thread renders, commit, UI thread mounts.
That works while the JS thread has nothing else to do. Now suppose a network response arrives mid-animation and parsing it takes 70 ms. At 60 fpsFrame rate (fps) / refresh rateFrame rate: how many new pictures the page produces per second. Refresh rate: how many times per second the screen can show a new one (60 Hz is common; many phones and laptops do 120 Hz). a frameFrameOne complete picture shown on the screen. Smooth motion is many frames per second, each slightly different, like the pages of a flip book. lasts 16.7 ms, so about four frames in a row get no new position. The card freezes, then jumps.
There are two standard ways to get the second picture.
1. The built-in Animated API with the native driver
Animated ships with React Native. You create an animated value, describe how it should change, and attach it to a style:
import { useEffect, type ReactNode } from "react";
import { Animated, useAnimatedValue } from "react-native";
export function FadeIn({ children }: { children: ReactNode }) {
const opacity = useAnimatedValue(0); // an Animated.Value that survives re-renders
useEffect(() => {
Animated.timing(opacity, {
toValue: 1,
duration: 300,
useNativeDriver: true, // ← hand the whole animation to the UI thread
}).start();
}, [opacity]);
return <Animated.View style={{ opacity }}>{children}</Animated.View>;
}useNativeDriver: true is the important line. With the native driverNative driverAn option of the built-in Animated library (useNativeDriver: true). The animation's description is sent to the native side once, and the UI thread computes every frame itself, without JavaScript., the description ("opacity from 0 to 1 over 300 ms") is sent to the native side once, and the UI thread computes each frame. The option is required: leave it out and React Native 0.88 warns that it "was not specified".
The limit: with its default settings in 0.88, the native driver only handles properties that don't change layout, mainly opacity, transform (move, scale, rotate), colours and border radius. Ask it to animate width or height and React Native logs "Style property 'width' is not supported by native animated module". This is the same reasoning as on the web, where transform and opacity are the cheap properties.
2. Reanimated: your own code on the UI thread
Following a finger is harder. The position isn't known in advance, so there is nothing to "describe once". The code that reacts to each touch has to run on the UI thread itself.
That's what the Reanimated library (4.7 here, with its companion react-native-worklets 0.13) makes possible. A JavaScript runtimeJavaScript runtimeOne running instance of a JavaScript engine, with its own global variables and its own thread to run on. Code in one runtime can't directly touch objects in another. is one running instance of the engine, with its own variables. Your app normally has one, on the JS thread. Reanimated starts a second runtime on the UI thread, and a workletWorkletA small JavaScript function that a build plugin copies into a second JavaScript runtime living on the UI thread, so it can run there every frame. Reanimated and Gesture Handler callbacks are worklets. is a small JavaScript function that a build plugin copies into it. A shared valueShared valueA Reanimated value (useSharedValue) that both the JS thread and UI-thread worklets can read and write. Changing it doesn't re-render the component; it updates the animated style directly. is a value both runtimes can read and write. Together with Gesture Handler (3.5 here), which recognizes gesturesGestureA touch movement with a meaning: tap, long press, pan (drag), pinch, swipe. A gesture recognizer watches the raw touches and decides which gesture is happening. natively, a draggable card looks like this:
import { useState } from "react";
import { Text } from "react-native";
import { GestureDetector, usePanGesture } from "react-native-gesture-handler";
import Animated, { useAnimatedStyle, useSharedValue, withSpring } from "react-native-reanimated";
import { scheduleOnRN } from "react-native-worklets";
export function SwipeCard() {
const x = useSharedValue(0); // lives where both threads can reach it
const [dismissed, setDismissed] = useState(false);
const pan = usePanGesture({
onUpdate: (e) => {
x.value = e.translationX; // runs on the UI thread, every frame
},
onDeactivate: () => { // the gesture ended: the finger lifted
if (Math.abs(x.value) > 120) {
scheduleOnRN(setDismissed, true); // hop to the JS thread to update React state
}
x.value = withSpring(0); // spring back, still on the UI thread
},
});
const style = useAnimatedStyle(() => ({ transform: [{ translateX: x.value }] }));
return (
<GestureDetector gesture={pan}>
<Animated.View style={style}>
<Text>{dismissed ? "Dismissed" : "Swipe me"}</Text>
</Animated.View>
</GestureDetector>
);
}Read it as two programs sharing one variable:
- On the UI thread:
onUpdateruns for every movement of the finger and writes the drag distance intox. The function passed touseAnimatedStylereruns wheneverxchanges and moves the native view. React never re-renders, and the JS thread isn't asked. - On the JS thread: everything else, including
setDismissed. React state lives there, so a worklet can't call the setter directly.scheduleOnRN(fn, ...args)queues the call on the JS thread.
GestureDetector only works inside a GestureHandlerRootView, a component from the same library that you wrap around your app once, near the root. The snippet type-checks against Gesture Handler 3.5 and against 3.3, the version the SDK 58 template pins. And if you've seen runOnJS in older Reanimated code: in react-native-worklets 0.13 it still exists but is marked deprecated in favour of scheduleOnRN.
For simple state-driven changes you don't need shared values at all. Reanimated 4 understands CSS-style transition properties on its animated components:
import { useState } from "react";
import { Pressable } from "react-native";
import Animated from "react-native-reanimated";
export function ExpandingBar() {
const [open, setOpen] = useState(false);
return (
<Pressable onPress={() => setOpen((o) => !o)}>
<Animated.View
style={{
height: 12,
backgroundColor: "tomato",
width: open ? 240 : 120, // state changes the target…
transitionProperty: "width", // …and Reanimated animates towards it
transitionDuration: 300,
}}
/>
</Pressable>
);
}Which one when
| Situation | Reach for |
|---|---|
| Fade, slide or scale something in, no finger involved | Animated with useNativeDriver: true, or a Reanimated transition |
Animate width, height, or anything that changes layout | Reanimated |
| Drag, swipe, pinch, pull-to-dismiss | Gesture Handler + Reanimated |
| A one-off change where a dropped frame doesn't matter | plain state is fine |
Device features, native modules and Expo
What the browser gave you for free
A browser is a huge standard library: networking, storage, the URL bar, permission prompts. In an app, each of those is a separate decision.
| On the web | In React Native | Notes |
|---|---|---|
fetch | fetch (built in) | Same API, implemented on top of the platform's networking. |
| CORSCORSCross-Origin Resource Sharing: response headers with which an API tells the browser that pages from other origins may read its responses. The request itself is usually sent (and acted on) either way, so CORS is not access control. errors | none | CORS is a rule browsers enforce for web pages. An app isn't a page, so no request is blocked by it. |
| cookies, sessions | usually a token (the string your server gives you at login to prove who you are) that you store yourself | See below for where. |
localStoragelocalStorageA small (a few MB) per-origin key–value store in the browser that survives reloads and restarts. Strings only, synchronous, and readable by any script on the page. | not available | Use a storage library. |
| URL + history | a navigation library (§06) | |
| a permissionPermission (mobile)The user's consent for an app to use something sensitive: camera, location, contacts, notifications. The app must declare it in its native config and ask at runtime; the user can say no. prompt on first use | declare it in the app's config and ask at runtime | Camera, location, notifications, contacts… |
| a tab that's open or closed | an app that's active, in the background, or killed by the system | AppState tells you which. |
fetch needs no import and works as you expect. Since a screen can disappear while a request is in flight, cancel it on cleanup, the pattern from React Hooks §07:
import { useEffect, useState } from "react";
import { Text } from "react-native";
type User = { id: string; name: string };
export function Profile({ userId }: { userId: string }) {
const [user, setUser] = useState<User | null>(null);
useEffect(() => {
const controller = new AbortController();
fetch(`https://api.example.com/users/${userId}`, { signal: controller.signal })
.then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json() as Promise<User>;
})
.then(setUser)
.catch((err: unknown) => {
if (!controller.signal.aborted) console.warn("profile failed", err);
});
return () => controller.abort(); // the screen closed or userId changed
}, [userId]);
return <Text>{user ? user.name : "Loading…"}</Text>;
}In a real app you'd let a data library do this, exactly as on the web. TanStack Query and friends run unchanged in React Native; see server state. Remember that phones lose their connection in lifts and tunnels far more often than laptops do, so retries and cached data matter more here.
Storage
There is no localStorage, and the right replacement depends on what you're storing:
| What | Where | Why |
|---|---|---|
| Preferences, small cached data | @react-native-async-storage/async-storage | Simple key–value strings on disk. Not encrypted. Every call returns a promise. |
| Tokens, passwords, anything secret | expo-secure-store | Kept in the operating system's Keychain / KeystoreKeychain / KeystoreThe operating system's encrypted storage for small secrets: Keychain on iOS, Keystore on Android. Other apps can't read your entries., encrypted, unreadable by other apps. |
| Lots of structured data, offline-first apps | expo-sqlite (a real SQL database) | Queries, indexes, transactions. |
| Very frequent small reads | react-native-mmkv | A fast synchronous store, called through JSI (§08). |
import AsyncStorage from "@react-native-async-storage/async-storage";
import * as SecureStore from "expo-secure-store";
type Settings = { theme: "light" | "dark"; fontSize: number };
// Ordinary preferences: plain text on disk, every call is async.
export async function saveSettings(settings: Settings): Promise<void> {
await AsyncStorage.setItem("settings", JSON.stringify(settings));
}
export async function loadSettings(): Promise<Settings | null> {
const raw = await AsyncStorage.getItem("settings"); // null when nothing was saved
return raw ? (JSON.parse(raw) as Settings) : null;
}
// Secrets: encrypted by the operating system (iOS Keychain, Android Keystore).
export async function saveToken(token: string): Promise<void> {
await SecureStore.setItemAsync("auth-token", token);
}
export async function loadToken(): Promise<string | null> {
return SecureStore.getItemAsync("auth-token");
}(Checked against AsyncStorage 3.1 and expo-secure-store 58. "light" | "dark" is a type that allows exactly those two strings.)
Native modules, and what Expo is
Each library in that table has two halves: JavaScript that you import, and a native moduleNative moduleA piece of Kotlin, Swift, Objective-C or C++ code that JavaScript can call, used to reach platform features with no JavaScript API: the camera, Bluetooth, the keychain, a payment SDK. written in Kotlin and Swift that does the real work. The native half must be compiled into your app, and npm install alone can't do that. Expo Go's limits, development builds and the rules for updates below are all consequences of this.
ExpoExpoA framework and set of tools on top of React Native: a project template, a CLI, a file-based router, about a hundred maintained native modules, and cloud services for building and updating apps. is the framework most React Native apps are built with. It's what create-expo-app (§02) set up, and it gives you:
- A library of native modules (
expo-camera,expo-location,expo-notifications,expo-secure-store, …) with consistent APIs, released together as an SDK version that is pinned to one React Native version. SDK 58 goes with React Native 0.88. - The Expo CLI (
npx expo start,npx expo run:ios) and the router from §06. - Generated native projects. A React Native app contains two native projects:
ios/, which XcodeXcode / Android StudioApple's and Google's own tools for building native apps. Xcode (Mac only) compiles the iOS project; Android Studio works with the Android one. Their logs show native build errors and crashes. (Apple's build tool) compiles, andandroid/, which GradleGradleAndroid's build tool. The android/ folder of an app is a Gradle project: Gradle compiles the Kotlin and C++ code and packages the app. (Android's build tool) compiles. With Expo you normally don't keep them in your repository: prebuildPrebuildnpx expo prebuild generates the ios/ and android/ native project folders from app.json and your installed packages, so you don't have to write or maintain them by hand. (npx expo prebuild) generates them fromapp.jsonand your installed packages. - EASEASExpo Application Services: Expo's hosted services. EAS Build compiles your iOS and Android apps in the cloud, EAS Submit uploads them to the stores, EAS Update delivers over-the-air updates., optional cloud services to build, submit and update the app.
Since the native folders are generated, you don't edit them by hand. A library that needs a native setting ships a config pluginConfig pluginA small function that edits the generated native projects during prebuild, e.g. to add a permission text to Info.plist or a line to AndroidManifest.xml. Libraries ship them so you don't edit native files yourself., and you configure it in app.json:
{
"expo": {
"name": "My Shop",
"scheme": "myshop",
"plugins": [
"expo-router",
["expo-secure-store", { "faceIDPermission": "Unlock your saved login with Face ID." }]
]
}
}During prebuild, that second plugin writes the sentence into the iOS project's Info.plist, where iOS requires a reason for using Face ID. You never open Xcode for it.
Expo Go vs a development build
You need an app on the phone to load your JavaScript into. There are two kinds:
| Expo GoExpo GoA ready-made app from the app stores that can load your JavaScript from your computer. Good for learning, but it only contains the native modules Expo chose to include. | Development buildDevelopment buildYour own app, compiled in debug mode with your own set of native modules, plus a developer menu. Like Expo Go, it loads JavaScript from your computer, but it contains exactly your native code. | |
|---|---|---|
| What it is | A ready-made app from the store | Your app, compiled in debug mode |
| Native modules inside | A fixed set chosen by Expo | Exactly the ones in your package.json |
| Setup | None: scan the QR code | One build per native change (npx expo run:ios, or EAS Build) |
| Good for | Learning, the first days of a project | Real projects |
Both load JavaScript from the dev server on your computer, so saving a file updates the app in about a second either way. The difference appears the day you install a library whose native code Expo Go doesn't contain: Expo Go can't run it, because that code was never compiled in. The template's own README calls Expo Go "a limited sandbox". Move to a development build early; from then on you only rebuild when the native side changes.
When you need your own native code
Most apps never do, because someone has already wrapped the camera, the maps and the payment SDK. You write a native module when you must call a platform API or a vendor SDK that has no wrapper, or when some computation is too heavy for JavaScript.
With Expo's module API, the native side is short. In Swift:
import ExpoModulesCore
import UIKit
public class BatteryModule: Module {
public func definition() -> ModuleDefinition {
Name("Battery")
Function("getLevel") { () -> Float in
UIDevice.current.isBatteryMonitoringEnabled = true
return UIDevice.current.batteryLevel // 0.0 … 1.0
}
}
}(This Swift file is the one snippet on the page we couldn't compile; its shape is copied from Expo SDK 58's own modules.) You don't need to know Swift to read it: a module named "Battery" exposes one function, getLevel, which asks iOS for the battery level and returns a number. A Kotlin file of the same shape does it for Android. JavaScript then gets a typed handle on it:
import { requireNativeModule } from "expo";
type BatteryModule = {
getLevel(): number;
};
export default requireNativeModule<BatteryModule>("Battery");This is the Expo counterpart of the TurboModule spec in §08, and it's called through JSI in the same way. (Expo SDK 58's own modules mostly use this definition() style; a few, such as expo-haptics, use a newer annotation style with @ExpoModule and @JS.)
Shipping, and updating without the store
Getting an app to users is slower than deploying a website. You build an app binaryApp binaryThe file a store delivers to phones: an .ipa for iOS, an .aab or .apk for Android. It contains the compiled native code, the JS bundle and the images., signCode signingStamping a build with your developer certificate, so the store and the phone can check who made the app and that nobody changed it afterwards. Unsigned apps can't be installed from the stores. it, upload it, wait for store reviewStore reviewThe check Apple and Google run on every new binary before it appears in the store. It takes from hours to days, and users then still have to update., and then wait for users to install the update. With EAS that's:
eas build --platform ios --profile production # compile and sign in the cloud
eas submit --platform ios # upload the build to App Store ConnectA profile is a named group of build settings in your eas.json file (production, preview, …). App Store Connect is Apple's website for managing your app's store listing and builds.
Now think about what's inside that binary. There are two layers: compiled native code, and a JS bundleJS bundleThe single file that holds all your app's JavaScript, produced by the Metro bundler. In a release build it is compiled to Hermes bytecode and placed inside the app., one file holding all your JavaScript. The native layer simply loads the bundle at startup. So nothing stops the app from loading a newer bundle that it downloaded from your server. That's an over-the-air updateOver-the-air (OTA) updateA new JavaScript bundle and assets that an installed app downloads from your server and uses on its next start, without the user installing a new version from the store.:
eas update --channel production --message "Fix checkout total"A channelUpdate channel (EAS)A named stream of over-the-air updates, such as production or staging. Each build is configured to listen to one channel and only receives updates published to it. is a named stream of updates. Each build is made to listen to one channel, so production builds only receive what you publish there. The installed app checks for an update when it starts (the default with expo-updates), downloads it in the background, and uses it on the next launch. A JavaScript-only fix can reach users in minutes, with no review queue.
Which changes can travel that way? Guess before you click each one:
The rule: if the change touches compiled code or native configuration, it needs a new binary. Everything else is JavaScript and assets.
That creates one real danger. Suppose build 1.4 is in users' hands, you then add a camera library, and you publish an update whose JavaScript calls it. Phones still on the 1.4 binary would run JavaScript that calls native code they don't have. The guard is the runtime versionRuntime versionA label for the native side of a build (which native code it contains). An OTA update is only delivered to installed apps whose runtime version matches the one it was made for.: a label stored in every binary and attached to every update. An update is only delivered to binaries with the same label. In app.json you choose how the label is derived, for example "runtimeVersion": { "policy": "fingerprint" }, which computes it from your native dependencies and configuration, so it changes exactly when the native layer does.
Performance and production
Debug and release are different programs
While developing you run a debug build, and it is much slower than what users get:
| Debug build | Release buildRelease buildThe optimized build you ship to users: no developer menu, no dev warnings, minified JavaScript compiled to bytecode and embedded in the app. A debug build is much slower and loads JavaScript from your computer. | |
|---|---|---|
| JavaScript comes from | the MetroMetroReact Native's bundler and dev server. It follows your imports, transforms TypeScript and JSX, and serves the result to the app on your phone or simulator. dev server on your computer | a bundle inside the app |
| Form of the JavaScript | readable source, sent over the network | minifiedMinifyRewrite code to be as small as possible without changing what it does: remove spaces and comments, shorten local names (calculateTotal → e), and simplify expressions., compiled to Hermes bytecodeBytecodeCompact instructions for a virtual machine instead of for a real processor. A Java compiler produces bytecode, and the JVM runs it on any computer that has a JVM, which is how one compiled program can run on many kinds of machines. |
| React | development mode: extra checks and warnings | production mode |
| Extras | developer menu, Fast Refresh, error overlay | none |
A release build, in turn, can't be inspected as easily. Test features in debug; measure speed in release (npx expo run:android --variant release, or an EAS build). And measure on a modest Android phone: your new iPhone is much faster than the typical phone your users hold.
Startup: what happens before the first screen
A cold startCold start (app)Launching an app that is not in memory: the system creates the process, native code starts up, the JavaScript loads and runs, and the first screen appears. The slowest kind of launch, and the one to measure. is launching an app that isn't in memory: from the tap on the icon to the first usable screen. While it runs, the system shows the splash screenSplash screenThe still image (usually a logo) that the operating system shows from the moment the user taps the icon until the app has something of its own to draw., a still image declared in the app's config.
HermesHermesThe JavaScript engine React Native ships with. It is built for phones: your code is compiled to bytecode on your build machine, so the app doesn't have to parse JavaScript at startup. is built for this phase. A browser engine receives JavaScript as text, and has to parse and compile it on the user's device. Hermes moves that work to your build machine: the release build runs the Hermes compiler (hermesc, with optimization on by default in 0.88's Android build) and ships bytecode, which the engine can start executing without a parsing step. By design Hermes favours quick starts and low memory use over the highest possible speed for long-running computation.
What you control is the "run app code" block. Every import at the top of a file runs when that file loads, and by default the whole bundle's top-level code runs before the first screen:
- Don't do work at import time. No big JSON parsing, no building lookup tables at the top of a module. Do it when a screen needs it.
- Load heavy screens lazily with
React.lazyor a dynamicimport(), the idea behind code splitting on the web. The file sizes matter less here (the bundle is already on the phone), but skipping the execution still helps. - Keep the splash screen until you're ready. The Expo template calls
SplashScreen.preventAutoHideAsync()so the user sees the splash image, not a white flash, while the first screen prepares.
Re-renders
Everything from How React Works applies, with a harsher penalty: each render of a big screen is JS-thread time that taps are waiting for (§07).
- Keep state as low in the tree as possible, so typing in a search box doesn't re-render the list under it.
- Lists:
memoon rows, stable keys,getItemLayout(§05). - Let the React CompilerReact CompilerA build-time tool (babel-plugin-react-compiler) that rewrites your components to cache values and elements automatically, so you need far fewer manual memo / useMemo / useCallback calls. do the memoizing where you can. The Expo template for SDK 58 turns it on (
"reactCompiler": trueunderexperimentsinapp.json). - Profile before changing anything. A guess about what re-renders is usually wrong.
Images
Images are the easiest way to waste memory on a phone. A 4000 × 3000 photo decoded for a 48 dp avatar can occupy 4000 × 3000 × 4 bytes ≈ 48 MB of memory once decoded at full size, however small it looks on screen.
- Ask your server or CDNCDNContent Delivery Network: servers spread around the world that keep copies of your files close to users, so they're served from a nearby city instead of your origin server. for a size close to what you display (remember §03: 48 dp on a 3× screen is 144 physical pixels).
- Give every image explicit dimensions, so the layout doesn't jump when it loads.
- Cache. The
expo-imagecomponent handles memory and disk caching and placeholders:
import { Image } from "expo-image";
export function Avatar({ url }: { url: string }) {
return (
<Image
source={{ uri: url }}
style={{ width: 48, height: 48, borderRadius: 24 }}
contentFit="cover"
cachePolicy="memory-disk" // keep it in memory and on disk
transition={150} // fade in over 150 ms
/>
);
}contentFit="cover" scales the picture to fill the box and crops the overflow, like CSS object-fit: cover.
Debugging
- React Native DevTools. Press
jin the terminal where the dev server runs. It opens a debugger built on Chrome's DevTools front end: Console, Sources with breakpoints, Network, a Performance timeline, and React's Components and Profiler panels. It talks to Hermes directly; the 0.88 dev server says it "can only be used with the Hermes engine". If you know browser DevTools, you know this. - The developer menu. Shake the device, or press
min the terminal. Reload, toggle the element inspector, show a performance overlay. - LogBox. In a debug build, errors and warnings appear as an overlay in the app. Read the first one; later ones are often consequences.
- Native problems (a crash at launch, a build error) don't show up in any of those. For them you read the logs in Xcode or Android StudioXcode / Android StudioApple's and Google's own tools for building native apps. Xcode (Mac only) compiles the iOS project; Android Studio works with the Android one. Their logs show native build errors and crashes.. With Expo that's rare, and usually means a library's native half is missing from the build (§10).
After release: you can't see their console
A user's phone has no terminal attached. You need crash reportingCrash reportingA service whose SDK runs inside your app, catches crashes and unhandled errors, and uploads them with a stack trace and device details, because you can't open the console on a user's phone.: an SDK inside the app that catches failures and uploads them. Sentry (@sentry/react-native) and Firebase Crashlytics are common choices. Two kinds of failure reach it:
- JavaScript errors: an exception in a handler or a render. The stack trace points into minified bytecode, so you must upload source mapsSource mapA file that maps the minified, bundled code back to your original source, so DevTools and error reports show your real file names and lines. at build time to see your own file names and lines. (
eas updatehas an--upload-source-mapsflag for exactly this.) - Native crashes: the app process dies in Kotlin, Swift or C++ code. These come with native stack traces, which are only readable with the platform's symbol files (the native counterpart of source maps, produced by the build).
Add an error boundary around each screen as well. That is a component which catches errors thrown while its children render and shows a fallback, so one broken component doesn't take the whole app down. With Expo Router, a route file can export a component named ErrorBoundary for this.
Testing, in one paragraph
Logic and components are tested as on the web: Jest with the jest-expo preset runs your code in Node, and React Native Testing Library (@testing-library/react-native) renders components and lets you query them by text and role, with the native side replaced by mocks. That covers most of what Unit Testing and Mocks, Stubs & Fakes teach. What it can't tell you is whether the real app works on a real OS: for that, an end-to-end tool such as Maestro or Detox drives a build in a simulator, with the same strengths and costs as on the web (End-to-End Testing). Keep that suite small, and include one test that installs the previous release and applies your next OTA update, because that's the path your users take.
React Native vs Flutter
Flutter is the other widely used way to build an iOS and an Android app from one codebase. It deserves its own deep-dive, and has one. Here is the short comparison, from the React Native side of the fence.
| React Native | Flutter | |
|---|---|---|
| Who draws the UI | iOS and Android, using their own views (§01) | Flutter's own rendering engine, on a blank canvas the platform provides |
| Language | TypeScript / JavaScript, run by the Hermes engine | Dart, compiled ahead of time to machine code for release builds |
| UI model | React components and hooks | Widgets; the idea of "UI as a function of state" is shared |
| Native look and feel | Real platform controls: a switch, a text field or a date picker is the system's, and picks up OS changes | Flutter's own re-creations of Material and iOS-style controls. Consistent across platforms, and identical on old and new OS versions |
| Layout and styling | Flexbox via Yoga, style objects (§03–§04) | Its own layout widgets (Row, Column, Padding…), no CSS-like layer |
| Reaching platform features | Native modules through JSI (§08, §10) | Plugins that talk to native code over "platform channels" |
| Ecosystem | npm: most JavaScript libraries run unchanged, plus the Expo SDK | pub.dev: a separate, Dart-only package world |
| Updates without the store | Supported by the architecture: swap the JS bundle (§10) | The app is compiled machine code; not part of the standard toolchain |
| Your existing skills | React and TypeScript carry over, and so can code shared with a web app | A new language and framework for a web developer |
What that means in practice
Pick React Native when your team already writes React, when you want to share logic or types with a web app, when the app should look and behave like the platform it runs on, or when shipping fixes over the air matters to you.
Pick Flutter when you want the UI to be pixel-identical everywhere (a heavily branded design, custom-drawn interfaces), when nobody on the team is invested in React, or when your targets go beyond phones to desktop and embedded screens, which Flutter supports as first-class targets.
Performance is not the deciding factor it's often made out to be. Both are fast enough for nearly every app when used well, and both can be made slow. React Native's risk is the JS thread (§07); Flutter's is work in its own build and paint phases. A badly virtualized list stutters in either.
Neither removes native knowledge entirely. Signing, store submission, permissions, push notifications and the occasional native crash are the same job in both. Expo hides much of it for React Native, and the day something breaks below that layer you'll be reading Xcode or Gradle output either way.
Pitfalls gallery
Each of these has cost someone an afternoon. Most were explained earlier; this is the list to scan when something looks wrong.
A number sneaks into a View
{count && <Badge />} renders 0 when count is 0. On the web you get a stray "0" on the page. In React Native a 0 directly inside a View is text outside <Text>: a development build reports the error "Text strings must be rendered within a <Text> component", and a release build reports nothing (§02). It often hides until the day a count really is zero.
<View>
<Text>Cart</Text>
{count && <Badge />}
</View><View>
<Text>Cart</Text>
{count > 0 && <Badge />}
</View>The screen is blank
Nothing renders and there's no error. Almost always a View somewhere between the root and your content has no height, so its flex: 1 children collapse to zero (§04). Give every wrapper in the chain flex: 1. A quick way to find the broken link is to put a bright backgroundColor on each level and see which one doesn't show.
Text runs off the right edge
In a row, children don't shrink (flexShrink is 0, §04). Yoga lets a long title be as wide as the whole row, not as wide as the space left beside the avatar, so each line can run past the right edge by about the avatar's width. Give the text flex: 1: it then takes exactly the remaining width, and wraps inside it.
<View style={{ flexDirection: "row", gap: 8 }}>
<View style={{ width: 48, height: 48 }} />
<Text>{title}</Text>
</View><View style={{ flexDirection: "row", gap: 8 }}>
<View style={{ width: 48, height: 48 }} />
<Text style={{ flex: 1 }}>{title}</Text>
</View>A long list in a ScrollView
items.map(…) inside a ScrollView mounts every row at once (§05). It feels fine with 30 test items and falls over with a real account's 3,000. Use FlatList for any list whose length you don't control, and never put a FlatList inside a ScrollView that scrolls the same way.
The keyboard covers the input
On the web the browser scrolls a focused input into view. In an app the keyboard slides up over the bottom of your screen, and whatever was there (often the very input being typed into) is hidden. KeyboardAvoidingView shrinks or pads its content by the keyboard's height:
export function Composer() {
const [text, setText] = useState("");
return (
<KeyboardAvoidingView
style={{ flex: 1 }}
behavior={Platform.OS === "ios" ? "padding" : undefined}
>
<View style={{ flex: 1 }} />
<TextInput value={text} onChangeText={setText} placeholder="Message" />
</KeyboardAvoidingView>
);
}The two platforms handle the keyboard differently, which is why behavior is set per platform here. On Android, Expo's default config (softwareKeyboardLayoutMode: "resize") asks the system to resize the window when the keyboard opens, but system bars and full-screen layouts change what you actually get. Test every form on both platforms, on a device, with the keyboard open.
It was only tested on one platform
"One codebase" doesn't mean "one behaviour". Things that commonly differ: the Android back button (§06), fonts and default text size, how shadows are drawn (iOS reads the shadow… styles, Android reads elevation; in 0.88 the boxShadow style is one way to write a shadow once for both), status bar behaviour, and permission prompts. Run both platforms before every release, and include a low-end Android phone.
It worked in development
Three versions of the same trap:
- Expo Go has it, your build doesn't (or the reverse). A native module must be compiled into the binary that runs your code (§10).
- The debug build hides or exaggerates slowness (§11). Check performance in a release build.
- An over-the-air update assumes native code that old binaries don't have (§10). Set a runtime version policy so updates only reach binaries they match.
Check yourself: predict what happens
Decide on an answer before you click. Every explanation points back to the section that covers it, and the behaviour described is that of React Native 0.88.
You run this in a development build. What does React Native 0.88 do?
export default function Hello() {
return <View>Hello</View>;
}<View style={{ flex: 1 }}>
<View style={{ width: 80, height: 80, backgroundColor: "red" }} />
<View style={{ width: 80, height: 80, backgroundColor: "green" }} />
<View style={{ width: 80, height: 80, backgroundColor: "blue" }} />
</View><View style={{ backgroundColor: "black", color: "white" }}>
<Text>Can you read me?</Text>
</View>An onPress handler runs a loop that takes 3 seconds. During those 3 seconds the user drags a ScrollView and then taps another button.
messages holds 5,000 items. How many rows does this FlatList render in its first render pass, before any batching or scrolling?
<FlatList
data={messages} // 5,000 items
keyExtractor={(m) => m.id}
renderItem={({ item }) => <Row text={item.text} />}
/>Animated.timing(width, {
toValue: 200,
duration: 300,
useNativeDriver: true,
}).start();
// …
<Animated.View style={{ width }} />On Monday you publish version 1.4 to the stores. On Tuesday you install a camera library, call it from a new screen, and publish only an over-the-air update. What happens on a phone that still runs the 1.4 binary?
A user scrolls a product list down to row 200, taps a product (a stack navigator pushes the detail screen), then taps Back.
Cheat sheet
<View> becomes a UIView or an Android View. No browser, no DOM, no WebView.View is a box. Text draws characters. Pressable + onPress replaces button + onClick.Text inside Text inherits. Numbers are density-independent pixels.flexDirection: column, flexShrink: 0. flex: 1 fills what's left. Respect the safe-area insets.getItemLayout for fixed heights.useNativeDriver: true for opacity and transforms; Reanimated worklets and shared values for gestures and layout.| If you want… | Write |
|---|---|
| Start a project | npx create-expo-app@latest my-app, then npx expo start |
| A box / text / button | <View> / <Text> / <Pressable onPress={…}> |
| A text field | <TextInput value={v} onChangeText={setV} /> |
| A remote image | <Image source={{ uri }} style={{ width: 96, height: 96 }} /> |
| Styles | const styles = StyleSheet.create({ card: { padding: 16 } }) |
| Conditional style | style={[styles.card, active && styles.active]} |
| A row | flexDirection: "row" |
| Fill the remaining space | flex: 1 (and on every parent up to the root) |
| Centre a child | justifyContent: "center", alignItems: "center" on the parent |
| Space between children | gap: 12 |
| Half the parent's width | width: "50%" |
| Avoid the notch | const insets = useSafeAreaInsets() from react-native-safe-area-context |
| Platform-specific value | Platform.select({ ios: a, default: b }) or Platform.OS === "android" |
| Screen size | const { width, height } = useWindowDimensions() |
| A long list | <FlatList data keyExtractor renderItem /> |
| Go to a screen (Expo Router) | <Link href="/product/42"> or router.push("/product/42") |
| Read a route param | const { id } = useLocalSearchParams<{ id: string }>() |
| A fade or slide | Animated.timing(v, { toValue, duration, useNativeDriver: true }).start() |
| Follow a finger | usePanGesture + useSharedValue + useAnimatedStyle |
| Call back into React from a worklet | scheduleOnRN(setState, value) |
| Save a preference | await AsyncStorage.setItem(key, JSON.stringify(value)) |
| Save a secret | await SecureStore.setItemAsync(key, token) |
| Open the debugger | press j in the dev server terminal |
| Build for the store | eas build --platform ios --profile production |
| Ship a JavaScript fix | eas update --channel production --message "…" |
Versions this page was checked against: React Native 0.88.1, React 19.3, Expo SDK 58 (expo-router 58), React Navigation 7.5, Reanimated 4.7 with react-native-worklets 0.13, Gesture Handler 3.5, react-native-safe-area-context 5.11, AsyncStorage 3.1, TypeScript 7.0.