React Native Cheatsheet

Networking

Use this React Native reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

fetch API

React Native includes the fetch API globally — no import needed.

// GET
const response = await fetch('https://api.example.com/users');
const data = await response.json();

// POST with JSON body
const response = await fetch('https://api.example.com/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${token}`,
  },
  body: JSON.stringify({ name: 'Alice', email: 'alice@example.com' }),
});

if (!response.ok) {
  throw new Error(`HTTP ${response.status}`);
}

const user = await response.json();

Response methods

MethodReturnsUse case
response.json()Promise\<any\>JSON body
response.text()Promise\<string\>Plain text
response.blob()Promise\<Blob\>Binary (images)
response.arrayBuffer()Promise\<ArrayBuffer\>Raw bytes
response.formData()Promise\<FormData\>Form data

Request options

OptionValuesNotes
method'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'Default: 'GET'
headersobjectKey-value header pairs
bodystring | FormData | BlobGET/HEAD cannot have body
signalAbortSignalCancellation
mode'cors' | 'no-cors' | 'same-origin'CORS mode
credentials'omit' | 'same-origin' | 'include'Cookies
cache'default' | 'no-cache' | 'no-store' | 'reload'

Cancellation with AbortController

useEffect(() => {
  const controller = new AbortController();

  async function load() {
    try {
      const res = await fetch('/api/data', { signal: controller.signal });
      const json = await res.json();
      setData(json);
    } catch (e) {
      if (e.name !== 'AbortError') setError(e);
    }
  }

  load();
  return () => controller.abort();
}, []);

Error Handling Pattern

async function fetchUser(id: string): Promise<User> {
  const response = await fetch(`/api/users/${id}`);

  if (!response.ok) {
    const body = await response.text();
    throw new Error(`${response.status}: ${body}`);
  }

  return response.json();
}

// Usage with try/catch
try {
  const user = await fetchUser('123');
  setUser(user);
} catch (error) {
  if (error instanceof Error) {
    setErrorMessage(error.message);
  }
}

Axios

npm install axios
import axios from 'axios';

// Create instance with defaults
const api = axios.create({
  baseURL: 'https://api.example.com',
  timeout: 10000,
  headers: { 'Content-Type': 'application/json' },
});

// Request interceptor — attach auth token
api.interceptors.request.use(config => {
  const token = getToken();
  if (token) config.headers.Authorization = `Bearer ${token}`;
  return config;
});

// Response interceptor — handle 401
api.interceptors.response.use(
  response => response,
  async error => {
    if (error.response?.status === 401) {
      await refreshToken();
      return api.request(error.config);  // retry
    }
    return Promise.reject(error);
  }
);

// GET
const { data } = await api.get<User[]>('/users', { params: { page: 1 } });

// POST
const { data: newUser } = await api.post<User>('/users', { name: 'Alice' });

// PUT / PATCH / DELETE
await api.put(`/users/${id}`, { name: 'Bob' });
await api.patch(`/users/${id}`, { name: 'Bob' });
await api.delete(`/users/${id}`);

// Error check
if (axios.isAxiosError(error)) {
  console.log(error.response?.status);
  console.log(error.response?.data);
}

// Cancellation
const controller = new AbortController();
await api.get('/data', { signal: controller.signal });
controller.abort();

File Upload (multipart/form-data)

// Using fetch
const formData = new FormData();
formData.append('file', {
  uri: imageUri,           // local file path from image picker
  name: 'photo.jpg',
  type: 'image/jpeg',
} as any);
formData.append('userId', '123');

const response = await fetch('/api/upload', {
  method: 'POST',
  headers: { 'Content-Type': 'multipart/form-data' },
  body: formData,
});

// Using axios
const formData = new FormData();
formData.append('file', { uri, name: 'photo.jpg', type: 'image/jpeg' } as any);

await api.post('/upload', formData, {
  headers: { 'Content-Type': 'multipart/form-data' },
  onUploadProgress: (e) => setProgress(e.loaded / (e.total ?? 1)),
});

WebSocket

const ws = new WebSocket('wss://example.com/socket');

ws.onopen = () => {
  console.log('Connected');
  ws.send(JSON.stringify({ type: 'ping' }));
};

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  handleMessage(data);
};

ws.onerror = (error) => console.error('WS error:', error);

ws.onclose = (event) => {
  console.log('Closed:', event.code, event.reason);
  if (event.code !== 1000) reconnect();  // unexpected close
};

// Send data
ws.send(JSON.stringify({ type: 'message', text: 'Hello' }));

// Close
ws.close(1000, 'Done');

// State
ws.readyState  // 0=CONNECTING, 1=OPEN, 2=CLOSING, 3=CLOSED

// Cleanup in useEffect
useEffect(() => {
  const socket = new WebSocket('wss://...');
  // ... setup handlers
  return () => socket.close();
}, []);

NetInfo — Network Status

npm install @react-native-community/netinfo
import NetInfo from '@react-native-community/netinfo';

// One-time check
const state = await NetInfo.fetch();
console.log(state.isConnected);    // true/false
console.log(state.type);           // 'wifi' | 'cellular' | 'none' | ...
console.log(state.details);        // platform-specific details

// Subscribe to changes
const unsubscribe = NetInfo.addEventListener(state => {
  setIsOffline(!state.isConnected);
});

// Cleanup
return () => unsubscribe();

NetInfo connection types

'none' | 'unknown' | 'cellular' | 'wifi' | 'bluetooth' | 'ethernet' | 'wimax' | 'vpn' | 'other'

Background Fetch / Push Notifications

# Expo
npx expo install expo-background-fetch expo-task-manager expo-notifications
import * as TaskManager from 'expo-task-manager';
import * as BackgroundFetch from 'expo-background-fetch';

const TASK_NAME = 'background-sync';

TaskManager.defineTask(TASK_NAME, async () => {
  try {
    await syncData();
    return BackgroundFetch.BackgroundFetchResult.NewData;
  } catch {
    return BackgroundFetch.BackgroundFetchResult.Failed;
  }
});

await BackgroundFetch.registerTaskAsync(TASK_NAME, {
  minimumInterval: 15 * 60,   // 15 minutes
  stopOnTerminate: false,
  startOnBoot: true,
});

GraphQL with Apollo Client

npm install @apollo/client graphql
import { ApolloClient, InMemoryCache, ApolloProvider, gql, useQuery, useMutation } from '@apollo/client';

const client = new ApolloClient({
  uri: 'https://api.example.com/graphql',
  cache: new InMemoryCache(),
  headers: { Authorization: `Bearer ${token}` },
});

// Wrap app
<ApolloProvider client={client}>
  <App />
</ApolloProvider>

// Query
const GET_USERS = gql`
  query GetUsers($limit: Int) {
    users(limit: $limit) {
      id
      name
      email
    }
  }
`;

function UserList() {
  const { data, loading, error, refetch } = useQuery(GET_USERS, {
    variables: { limit: 20 },
    fetchPolicy: 'cache-and-network',
  });

  if (loading) return <ActivityIndicator />;
  if (error) return <Text>Error: {error.message}</Text>;

  return (
    <FlatList
      data={data.users}
      keyExtractor={item => item.id}
      renderItem={({ item }) => <Text>{item.name}</Text>}
    />
  );
}

// Mutation
const CREATE_USER = gql`
  mutation CreateUser($name: String!, $email: String!) {
    createUser(name: $name, email: $email) { id name }
  }
`;

const [createUser, { loading }] = useMutation(CREATE_USER, {
  refetchQueries: [{ query: GET_USERS }],
  onCompleted: (data) => console.log(data.createUser),
  onError: (error) => console.error(error),
});

createUser({ variables: { name: 'Alice', email: 'alice@ex.com' } });

Gotcha: React Native does not have XMLHttpRequest progress events for downloads — use the community library react-native-fs or expo-file-system for download progress tracking.