React Native cheat sheet
Key ideas
- TypeScript
nullandundefinedare distinct types;== nullcatches both,=== nullcatches onlynull, and??/?.handle both. useStatereads its argument on the first render only; use the updater formsetCount(c => c + 1)when the new value depends on the old one.useEffectmust list every value from the component body in its dependency array; a missing entry produces a stale closure.- Since React Navigation 7,
navigateno longer pops an existing screen; usepopToorgoBackto go back. - TurboModules are lazy: the native instance is created on first JS access; synchronous spec methods run on the JS thread,
Promise<T>methods are async. FlatListvirtualizes by unmounting off-screen rows; it does not recycle likeRecyclerView. FlashList recycles for very long lists.- Zustand selectors (
useAuthStore((s) => s.token)) re-render only when the selected slice changes; reading the whole store re-renders on every field change. constprevents reassignment of the binding, not mutation of the object—identical to Kotlin'sval.- A discriminated union with a
neverdefault check is TypeScript's equivalent of a Kotlinsealed class. - Judge performance on a release build; debug builds run React in development mode with extra checks that slow rendering.
APIs at a glance
| API or term | Use it for |
|---|---|
strictNullChecks | enable in tsconfig.json via strict: true to make null/undefined type-safe |
useState | component state; argument is read only on the first render, pass a function for costly init |
useEffect | side effects after render; return a cleanup function for subscriptions, timers, connections |
useCallback | keep a stable function reference between renders; pair with React.memo or a dependency array |
useRef | hold a mutable value that survives re-renders without triggering them (timer ID, previous value, native view ref) |
createNativeStackNavigator | native stack navigation via react-native-screens; screens below the top stay mounted |
create (Zustand) | global client state; read with a selector so the component re-renders only on that slice |
useQuery / useMutation | TanStack Query server-state caching; call invalidateQueries after a mutation to refetch |
TurboModuleRegistry.getEnforcing | fetch a required native module; throws if the module is missing, unlike get which returns null |
FlatList | virtualized list that unmounts off-screen rows; use getItemLayout for fixed-size rows |
Reanimated worklets | run animations on the UI thread so they stay smooth while the JS thread is busy |
codegenConfig | in package.json to point Codegen at spec files; the Native prefix is required for discovery |
Snippets
Discriminated union with exhaustiveness check
type User = { id: number; name: string };
type Action =
| { type: "FETCH"; id: number }
| { type: "SET"; user: User }
| { type: "CLEAR" };
function handleAction(action: Action): string {
switch (action.type) {
case "FETCH": return `fetching ${action.id}`;
case "SET": return `set ${action.user.name}`;
case "CLEAR": return "cleared";
default: {
const unhandled: never = action; // compile error if a case is missing
return unhandled;
}
}
}Zustand client state + TanStack Query server state
import { create } from 'zustand';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
type AuthState = {
token: string | null;
signIn: (token: string) => void;
signOut: () => void;
};
export const useAuthStore = create<AuthState>()((set) => ({
token: null,
signIn: (token: string) => set({ token }),
signOut: () => set({ token: null }),
}));
type Account = { id: string; balance: number };
async function fetchAccount(id: string, signal: AbortSignal): Promise<Account> {
const res = await fetch(`https://api.example.com/accounts/${id}`, { signal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
async function postTransfer(id: string, amount: number): Promise<void> {
const res = await fetch(`https://api.example.com/accounts/${id}/transfers`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ amount }),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
}
export function useAccount(accountId: string) {
const client = useQueryClient();
const account = useQuery({
queryKey: ['account', accountId],
queryFn: ({ signal }) => fetchAccount(accountId, signal),
});
const transfer = useMutation({
mutationFn: (amount: number) => postTransfer(accountId, amount),
onSuccess: () => client.invalidateQueries({ queryKey: ['account', accountId] }),
});
return { account, transfer };
}Memoized FlatList row with fixed layout
import { memo, useCallback } from 'react';
import { FlatList, ListRenderItem, StyleSheet, Text, View } from 'react-native';
type Item = { id: string; label: string };
const ROW_HEIGHT = 56;
const styles = StyleSheet.create({
row: { height: ROW_HEIGHT, justifyContent: 'center', paddingHorizontal: 16 },
});
const Row = memo(function Row({ label }: { label: string }) {
return <View style={styles.row}><Text>{label}</Text></View>;
});
const getItemLayout = (_: ArrayLike<Item> | null | undefined, index: number) => ({
length: ROW_HEIGHT,
offset: ROW_HEIGHT * index,
index,
});
export function ItemList({ items }: { items: Item[] }) {
const renderItem = useCallback<ListRenderItem<Item>>(
({ item }) => <Row label={item.label} />,
[]
);
return (
<FlatList
data={items}
keyExtractor={(item) => item.id}
renderItem={renderItem}
getItemLayout={getItemLayout}
/>
);
}TurboModule spec (sync + async methods)
import type { TurboModule } from 'react-native';
import { TurboModuleRegistry } from 'react-native';
export interface Spec extends TurboModule {
shortHash(input: string): string; // sync, JS thread
sha256(input: string): Promise<string>; // async, background thread
}
export default TurboModuleRegistry.getEnforcing<Spec>('NativeHasher');Rules of thumb
- Prefer
unknownoverany; narrow with anischeck before use, just like Kotlin'sAny?. - Never mutate state in place; create a new object or array so React and Zustand selectors detect the change.
- Prefer
popToorgoBackovernavigatewhen going to a screen already in the stack (React Navigation 7+). - Never do I/O in a synchronous TurboModule spec method; return a
Promise<T>and run the work on a background thread. - Prefer
useCallbackwith a full dependency array; an empty array freezes values from the first render. - Never use the array index as
keyExtractor; use a stable id so React matches rows correctly on insert, remove, or reorder.
Gotchas
- Checking only for null on optional properties. Optional properties (
email?: string) are typed asstring | undefined, so=== nullmisses the common case. Use== nullor??to cover both. - Forgetting to await a Promise. Calling
fetchUser(id)withoutawaitreturns aPromise, not aUser; the request runs but nothing waits and a failure becomes an unhandled rejection. Enableno-floating-promisesin typescript-eslint. - Omitting a value from the useEffect dependency array. The effect keeps using the value from the render that created it (stale closure). List every value from the component body that the effect reads;
react-hooks/exhaustive-depscatches omissions. - Using navigate to go back in React Navigation 7.
navigateto a lower screen pushes a new copy instead of popping. UsegoBackorpopToto remove screens from the stack. - Creating new objects or inline callbacks in render and passing them to React.memo rows. A new
styleobject or callback each render makes the shallow compare fail, so the row re-renders every time. Hoist styles intoStyleSheet.createand stabilize callbacks withuseCallback. - Heavy work in a TurboModule constructor. The constructor runs on first access, often during a user interaction, blocking the JS thread. Keep the constructor cheap and start expensive setup lazily or on a background thread.
Quick interview answers
How does TypeScript handle null and undefined compared to Kotlin?
TypeScript has two distinct types, null and undefined, while Kotlin has only null. With strictNullChecks enabled, == null is true for both values, === null is true only for null, and ?? / ?. handle both in one expression.
What is the difference between FlatList and Android's RecyclerView?
FlatList virtualizes by unmounting rows that leave the visible window and re-rendering them from scratch when they return, whereas RecyclerView recycles row view holders. For very long or complex lists, FlashList adds recycling similar to RecyclerView.
How do TurboModules differ from legacy React Native modules?
TurboModules are lazy: the native instance is created on first JS access, and a TypeScript spec is compiled by Codegen into a Java class that the Kotlin module extends. Legacy @ReactMethod modules still load through an interop layer but skip Codegen's type checks, so mismatches surface only at runtime.
Why keep server data in TanStack Query instead of Zustand or Redux?
Storing server data in a client store forces you to handle caching, refetching, and invalidation by hand, and copies can drift from the server. TanStack Query owns that lifecycle: you identify data with a query key and call invalidateQueries after a mutation to refetch active queries.
What changed with navigate in React Navigation 7?
Since React Navigation 7, navigate no longer pops to an existing screen in the stack; it pushes a new copy. To go back, use goBack or popTo, and use push when you intentionally want a duplicate screen.
When is a useEffect cleanup function called and why does it matter?
React calls the cleanup function before the effect re-runs and on unmount, similar to onDispose in Compose's DisposableEffect. Without it, a listener, timer, or subscription leaks on every mount, and StrictMode's extra mount-unmount-mount in development makes the leak show up twice.