Mobile Apps (React Native)

Lists, Data and Forms

35 मिनट

FlatList

Never render long lists with .map() inside a ScrollView: it renders everything at once. FlatList renders only what is visible.

import { FlatList, RefreshControl, Text, View } from "react-native";

export default function Tracks() {
  const { data, isPending, error, refetch, isRefetching } = useQuery({
    queryKey: ["tracks"],
    queryFn: () => api.get("/v1/tracks"),
  });

  if (isPending) return <Text>Loading…</Text>;
  if (error) return <Text>Could not load tracks.</Text>;

  return (
    <FlatList
      data={data.items}
      keyExtractor={item => item.slug}
      renderItem={({ item }) => <TrackRow track={item} />}
      ItemSeparatorComponent={() => <View style={{ height: 1, backgroundColor: "#e5e7eb" }} />}
      refreshControl={<RefreshControl refreshing={isRefetching} onRefresh={refetch} />}
      onEndReached={loadMore}
      onEndReachedThreshold={0.5}
    />
  );
}

TanStack Query works the same as on the web and gives caching and retries.

Talking to your API

const API = process.env.EXPO_PUBLIC_API_URL;
export const api = {
  async get(path) {
    const res = await fetch(`${API}${path}`, { headers: await authHeaders() });
    if (!res.ok) throw new Error(`${res.status}`);
    return res.json();
  },
};

EXPO_PUBLIC_ variables are bundled into the app and visible to anyone who unpacks it. Never put secrets in a mobile app: anything shipped to devices can be extracted. Secrets live on your server; the app calls your API.

Forms on mobile

<TextInput
  value={email}
  onChangeText={setEmail}
  placeholder="you@example.com"
  keyboardType="email-address"
  autoCapitalize="none"
  autoComplete="email"
  textContentType="emailAddress"
  returnKeyType="next"
  style={styles.input}
/>
  • Choose the right keyboardType and autofill hints.
  • Wrap forms in KeyboardAvoidingView so the keyboard does not cover inputs.
  • Show validation errors under fields; disable submit while sending.

Offline and slow networks

Mobile connections drop. Show cached data when offline, retry failed requests, and tell users when an action is queued. Libraries such as TanStack Query's persistence or a local database (SQLite via expo-sqlite) help.

Exercise

Build a tracks screen that loads from an API with pull-to-refresh and infinite scroll, and a sign-up form with proper keyboards, autofill and inline validation.

Check yourself

  • Why use FlatList instead of map in a ScrollView?
  • Why can't mobile apps hold API secrets?
  • Which TextInput props improve email entry?

आपकी प्रगति केवल इसी ब्राउज़र में सहेजी जाती है।

समीक्षा के लिए भेजें (10 अंक)