React Native cheat sheet

Revise React Native core: TypeScript null safety, hooks, React Navigation, Zustand, TanStack Query, TurboModules, and FlatList performance.

Key ideas

  1. TypeScript null and undefined are distinct types; == null catches both, === null catches only null, and ?? / ?. handle both.
  2. useState reads its argument on the first render only; use the updater form setCount(c => c + 1) when the new value depends on the old one.
  3. useEffect must list every value from the component body in its dependency array; a missing entry produces a stale closure.
  4. Since React Navigation 7, navigate no longer pops an existing screen; use popTo or goBack to go back.
  5. 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.
  6. FlatList virtualizes by unmounting off-screen rows; it does not recycle like RecyclerView. FlashList recycles for very long lists.
  7. Zustand selectors (useAuthStore((s) => s.token)) re-render only when the selected slice changes; reading the whole store re-renders on every field change.
  8. const prevents reassignment of the binding, not mutation of the object—identical to Kotlin's val.
  9. A discriminated union with a never default check is TypeScript's equivalent of a Kotlin sealed class.
  10. 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 termUse it for
strictNullChecksenable in tsconfig.json via strict: true to make null/undefined type-safe
useStatecomponent state; argument is read only on the first render, pass a function for costly init
useEffectside effects after render; return a cleanup function for subscriptions, timers, connections
useCallbackkeep a stable function reference between renders; pair with React.memo or a dependency array
useRefhold a mutable value that survives re-renders without triggering them (timer ID, previous value, native view ref)
createNativeStackNavigatornative 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 / useMutationTanStack Query server-state caching; call invalidateQueries after a mutation to refetch
TurboModuleRegistry.getEnforcingfetch a required native module; throws if the module is missing, unlike get which returns null
FlatListvirtualized list that unmounts off-screen rows; use getItemLayout for fixed-size rows
Reanimated workletsrun animations on the UI thread so they stay smooth while the JS thread is busy
codegenConfigin 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 unknown over any; narrow with an is check before use, just like Kotlin's Any?.
  • Never mutate state in place; create a new object or array so React and Zustand selectors detect the change.
  • Prefer popTo or goBack over navigate when 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 useCallback with 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 as string | undefined, so === null misses the common case. Use == null or ?? to cover both.
  • Forgetting to await a Promise. Calling fetchUser(id) without await returns a Promise, not a User; the request runs but nothing waits and a failure becomes an unhandled rejection. Enable no-floating-promises in 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-deps catches omissions.
  • Using navigate to go back in React Navigation 7. navigate to a lower screen pushes a new copy instead of popping. Use goBack or popTo to remove screens from the stack.
  • Creating new objects or inline callbacks in render and passing them to React.memo rows. A new style object or callback each render makes the shallow compare fail, so the row re-renders every time. Hoist styles into StyleSheet.create and stabilize callbacks with useCallback.
  • 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.

Go deeper