Skip to content
Tutorials Center
My learning

Topics

Lesson 69 of 71 ยท Practice and Review

Exercises: Navigation, Data and Performance

Nine React Native exercises on navigation stacks, typed params, auth flows, storage migrations, query caching, optimistic updates and list tuning, with solutions.

The basic exercises were about drawing screens. These nine are about everything that makes an app feel real: moving between screens, remembering data across launches, talking to a server without hammering it, and keeping long lists smooth. They draw on navigation, typed params, auth flows, storage, TanStack Query and list performance.

Read-only and stand-in. React Navigation, AsyncStorage, TanStack Query and FlatList need a native runtime, so their real code is shown in plain code blocks. The live examples are small stand-ins written in plain JavaScript that reproduce the idea: a stack reducer, a storage adapter with a migration, a query cache with a fake clock, and the arithmetic behind list windowing. They are not the libraries; each one says what it simplifies.

Work the way you would in a real project: write the plan first. For each exercise, decide what the data looks like, which function owns the logic, and how you would check it. Hints are folded; open them only after a real attempt.

1. A stack as plain data

A navigation stack is just a history list. Write a reducer for it with four actions: push (add a screen on top), pop (remove the top screen, but never the last one), replace (swap the top screen) and popToTop (keep only the first screen).

Show hint

Represent the stack as an array of { name, params }. Every action returns a new array: [...stack, entry], stack.slice(0, -1), [...stack.slice(0, -1), entry], stack.slice(0, 1). For pop, return the same array when its length is 1; returning the same reference tells React nothing changed.

Show solution
TypeScript
type Entry = { name: string; params?: Record<string, unknown> };
type Action =
  | { type: 'push'; name: string; params?: Entry['params'] }
  | { type: 'pop' }
  | { type: 'replace'; name: string; params?: Entry['params'] }
  | { type: 'popToTop' };

export function stackReducer(stack: Entry[], action: Action): Entry[] {
  switch (action.type) {
    case 'push':
      return [...stack, { name: action.name, params: action.params }];
    case 'pop':
      return stack.length > 1 ? stack.slice(0, -1) : stack;
    case 'replace':
      return [...stack.slice(0, -1), { name: action.name, params: action.params }];
    case 'popToTop':
      return stack.length > 1 ? stack.slice(0, 1) : stack;
  }
}

The real library keeps richer state (keys, route names, nested navigators), but the core idea is the same: screens are a list and "back" removes the last one.

The stand-in below runs a scripted sequence of actions through this reducer and prints the stack after each step. Notice the pop on a single-screen stack that changes nothing.

Exercise 1: a navigation stack reducer

2. Typed navigation

Declare the screens of a stack: Home takes no params, Product needs a string id and an optional source. Write the Product screen so TypeScript knows route.params.id is a string, and so navigation.navigate('Product') without an id is a compile error.

Show hint

Define a RootStackParamList type that maps each route name to its params (undefined for none). Pass it to createNativeStackNavigator<RootStackParamList>() and use NativeStackScreenProps<RootStackParamList, 'Product'> for the screen's props.

Show solution
TSX
import { createNativeStackNavigator, NativeStackScreenProps } from '@react-navigation/native-stack';

export type RootStackParamList = {
  Home: undefined;
  Product: { id: string; source?: 'search' | 'home' };
};

const Stack = createNativeStackNavigator<RootStackParamList>();

type ProductProps = NativeStackScreenProps<RootStackParamList, 'Product'>;

function ProductScreen({ route, navigation }: ProductProps) {
  const { id, source } = route.params;      // id: string, source: 'search' | 'home' | undefined
  return (
    <Pressable onPress={() => navigation.navigate('Home')}>
      <Text>Product {id} from {source ?? 'unknown'}</Text>
    </Pressable>
  );
}

// navigation.navigate('Product')                  // error: params are required
// navigation.navigate('Product', { id: 42 })      // error: id must be a string

Hooks such as useNavigation() are untyped unless you declare the global ReactNavigation.RootParamList interface once; the NativeStackScreenProps approach types props without any global declaration.

3. Show different screens for signed-in users

Build the root navigator so a signed-out user only has a SignIn screen, a signed-in user only has Home and Settings, and nothing flashes while the saved token is still being read at startup.

Show hint

Do not call navigate('Home') after signing in. Render different Stack.Screens depending on the auth state. React Navigation then switches the whole stack and the signed-out screens cannot be reached by going back. Add a third state, loading, and show a splash view (or keep the native splash screen) until the token has been read.

Show solution
TSX
function RootNavigator() {
  const { status } = useAuth();   // 'loading' | 'signedOut' | 'signedIn'

  if (status === 'loading') {
    return <SplashView />;        // or keep expo-splash-screen visible
  }

  return (
    <Stack.Navigator>
      {status === 'signedIn' ? (
        <>
          <Stack.Screen name="Home" component={HomeScreen} />
          <Stack.Screen name="Settings" component={SettingsScreen} />
        </>
      ) : (
        <Stack.Screen name="SignIn" component={SignInScreen} options={{ headerShown: false }} />
      )}
    </Stack.Navigator>
  );
}

Because the screens are conditional, signing out removes Home and Settings from the tree and the app lands on SignIn by itself. See Deep Linking and Authentication Flows for redirects after login.

Storage

4. Load settings safely, with a migration

Version 1 of your app saved {"darkMode": true}. Version 2 wants {"version": 2, "theme": "dark" | "light", "fontScale": 1}. Write loadSettings(storage) that returns version 2 settings no matter what is stored: nothing, a version 1 object, version 2, or corrupt text. After migrating, it should save the new shape.

Show hint

Storage only holds strings, so you JSON.stringify on write and JSON.parse on read. Parsing can throw, so wrap it in try/catch and fall back to defaults. Check version to decide what to do: undefined with a darkMode key means version 1. Write the migrated value back so the work happens once.

Show solution
TypeScript
import AsyncStorage from '@react-native-async-storage/async-storage';

const KEY = 'settings';
type Settings = { version: 2; theme: 'dark' | 'light'; fontScale: number };
const defaults: Settings = { version: 2, theme: 'light', fontScale: 1 };

export async function loadSettings(): Promise<Settings> {
  const raw = await AsyncStorage.getItem(KEY);
  if (raw === null) return defaults;

  let data: any;
  try {
    data = JSON.parse(raw);
  } catch {
    return defaults;                 // corrupt: start fresh
  }

  if (data?.version === 2) return { ...defaults, ...data };

  if (typeof data?.darkMode === 'boolean') {        // version 1
    const migrated: Settings = { ...defaults, theme: data.darkMode ? 'dark' : 'light' };
    await AsyncStorage.setItem(KEY, JSON.stringify(migrated));
    return migrated;
  }
  return defaults;
}

Real AsyncStorage also returns promises, so the function is async. The stand-in below uses an in-memory object with the same getItem and setItem shape.

Exercise 4: settings with a migration

5. Where does it go?

For each item, choose AsyncStorage (or MMKV), SecureStore, or neither: a refresh token, the chosen theme, a draft note, a password typed in a form, a list of recently viewed product ids, a payment card number.

Show hint

Ask two questions. Would exposing this value harm the user if someone read the phone's backup or a rooted device? And does the app really need to keep it between launches? Preferences and caches are cheap to store openly; credentials need the Keychain or Keystore; some data should never be stored at all.

Show solution
Item Where Why
Refresh token SecureStore A credential: it is backed by the iOS Keychain and Android Keystore
Chosen theme AsyncStorage / MMKV A harmless preference
Draft note AsyncStorage / MMKV (or SQLite for many notes) User data that should survive a restart, not secret
Password typed in a form Neither Send it to the server over HTTPS and discard it; keep only the token you get back
Recently viewed ids AsyncStorage / MMKV Small, harmless cache
Payment card number Neither Let the payment provider's SDK handle it; never store raw card data yourself

AsyncStorage is plain, unencrypted storage. Treat it as readable by anyone who gets at the device files.

Server data

6. A cache that does not refetch needlessly

Write a tiny fetchQuery(key, fn) with a staleTime. If the data for a key is fresh (younger than staleTime), return it without calling fn. If it is stale, call fn again. If two callers ask for the same key while a request is in flight, they must share one request.

Show hint

Keep a Map from key to { data, updatedAt, promise }. When asked: if data exists and now - updatedAt < staleTime, return it. If a promise is in flight, return that same promise. Otherwise start fn(), store the promise, and on success store the data and the time. Clear the promise in finally. A fake clock you control makes the behaviour easy to check.

Show solution
TypeScript
type Entry<T> = { data?: T; updatedAt: number; promise?: Promise<T> };

export function createQueryCache(staleTime: number, now: () => number = Date.now) {
  const entries = new Map<string, Entry<any>>();

  return async function fetchQuery<T>(key: string, fn: () => Promise<T>): Promise<T> {
    const entry = entries.get(key) ?? { updatedAt: 0 };
    entries.set(key, entry);

    if (entry.data !== undefined && now() - entry.updatedAt < staleTime) {
      return entry.data;
    }
    if (entry.promise) return entry.promise;

    entry.promise = fn()
      .then((data) => {
        entry.data = data;
        entry.updatedAt = now();
        return data;
      })
      .finally(() => {
        entry.promise = undefined;
      });
    return entry.promise;
  };
}

TanStack Query does this and much more (garbage collection, retries, background refetching, focus and reconnect handling). The goal here is to see the two ideas, freshness and request sharing, in a dozen lines.

Exercise 6: staleTime and request sharing

7. An optimistic like with rollback

A feed shows posts with a heart. Tapping the heart should fill it immediately, send the request in the background, and undo the change if the request fails. Write the mutation with TanStack Query v5.

Show hint

The useMutation options onMutate, onError and onSettled map to "before the request", "if it failed" and "either way". In onMutate, cancel in-flight queries for that key, save the current data, write the optimistic data with setQueryData, and return the saved data as the context. onError receives that context.

Show solution
TSX
import { useMutation, useQueryClient } from '@tanstack/react-query';

type Post = { id: string; liked: boolean };

export function useToggleLike() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (id: string) => api.toggleLike(id),

    onMutate: async (id) => {
      await queryClient.cancelQueries({ queryKey: ['posts'] });
      const previous = queryClient.getQueryData<Post[]>(['posts']);
      queryClient.setQueryData<Post[]>(['posts'], (old = []) =>
        old.map((p) => (p.id === id ? { ...p, liked: !p.liked } : p)),
      );
      return { previous };
    },

    onError: (_error, _id, context) => {
      queryClient.setQueryData(['posts'], context?.previous);
    },

    onSettled: () => {
      queryClient.invalidateQueries({ queryKey: ['posts'] });
    },
  });
}

Cancelling first stops an older fetch from overwriting your optimistic value. Invalidating at the end makes the screen match the server whether the request succeeded or not.

Performance

8. How many rows does a list actually render?

FlatList renders rows inside a window around the visible area, measured in viewport heights. Given a viewport of 800 points, rows of 80 points, windowSize of 5 and a scroll offset, compute which rows are rendered. Then explain why getItemLayout helps.

Show hint

windowSize counts viewports: 5 means the visible one plus two above and two below. So the rendered area is offset - 2 * viewport to offset + viewport + 2 * viewport. Divide by the row height to turn points into indexes, and clamp to the data length. Without getItemLayout, the list must measure each row after rendering it to know where things are; with fixed rows it can compute positions directly.

Show solution
TypeScript
export function renderedRange(opts: {
  offset: number; viewport: number; rowHeight: number; windowSize: number; count: number;
}) {
  const { offset, viewport, rowHeight, windowSize, count } = opts;
  const extra = ((windowSize - 1) / 2) * viewport;
  const first = Math.max(0, Math.floor((offset - extra) / rowHeight));
  const last = Math.min(count - 1, Math.ceil((offset + viewport + extra) / rowHeight) - 1);
  return { first, last, rendered: last - first + 1 };
}

On a real list, pass getItemLayout={(_, index) => ({ length: 80, offset: 80 * index, index })} when rows have a fixed height. Then jumping with scrollToIndex or scrolling fast needs no measuring. The real algorithm also batches work (maxToRenderPerBatch) and renders initialNumToRender rows first, so this is a simplified model.

Exercise 8: the virtualization window

9. Tune a janky list

A product list stutters while scrolling. Its code creates a new renderItem function and a new onPress closure on every render, the row component is not memoized, and the key is String(index). Rewrite it.

TSX
function Products({ products, onSelect }) {
  return (
    <FlatList
      data={products}
      keyExtractor={(_, index) => String(index)}
      renderItem={({ item }) => (
        <ProductRow item={item} onPress={() => onSelect(item.id)} />
      )}
    />
  );
}
Show hint

Three fixes: a stable keyExtractor based on the item id (defined once outside the component), a memo row that receives the id and a stable callback instead of an inline closure, and a useCallback for renderItem. If rows have a fixed height, add getItemLayout. Measure before and after; do not tune blindly.

Show solution
TSX
import { memo, useCallback } from 'react';
import { FlatList, Pressable, Text } from 'react-native';

const ROW_HEIGHT = 72;
const keyExtractor = (p: Product) => p.id;
const getItemLayout = (_: unknown, index: number) => ({
  length: ROW_HEIGHT,
  offset: ROW_HEIGHT * index,
  index,
});

const ProductRow = memo(function ProductRow({
  item,
  onSelect,
}: {
  item: Product;
  onSelect: (id: string) => void;
}) {
  return (
    <Pressable style={{ height: ROW_HEIGHT, padding: 16 }} onPress={() => onSelect(item.id)}>
      <Text>{item.name}</Text>
    </Pressable>
  );
});

export function Products({ products, onSelect }: Props) {
  const renderItem = useCallback(
    ({ item }: { item: Product }) => <ProductRow item={item} onSelect={onSelect} />,
    [onSelect],
  );

  return (
    <FlatList
      data={products}
      keyExtractor={keyExtractor}
      renderItem={renderItem}
      getItemLayout={getItemLayout}
      windowSize={7}
      initialNumToRender={12}
    />
  );
}

The row now receives the same item object and the same onSelect function until they actually change, so memo can skip it. The onSelect passed from the parent must itself be stable (wrap it in useCallback there). Profile with the tools from Debugging and Performance Profiling to confirm the improvement.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. After a user signs in, what is the cleanest way to move from SignIn to Home with React Navigation?

    Conditional screens swap the whole stack when auth state changes, so signed-out screens are unreachable and no manual navigation is needed.
  2. 2. Why wrap JSON.parse of stored text in try/catch?

    Stored strings are outside your control. A crash while loading settings would stop the app from starting.
  3. 3. Where should a refresh token be stored?

    Credentials belong in encrypted, OS-protected storage. AsyncStorage is plain text, and the bundle is readable by anyone.
  4. 4. In an optimistic mutation, what is the job of onError?

    onMutate saves the previous data and returns it as context; onError puts it back if the request fails.
  5. 5. What does getItemLayout let a FlatList skip?

    With fixed-height rows the list can compute each row's offset directly instead of measuring after render.

Summary

  • A navigation stack is a list of screens; push, pop, replace and pop-to-top are small pure functions. Use typed param lists so wrong params are compile errors, and conditional screens for auth.
  • Storage holds strings: parse defensively, version your data and migrate it on load.
  • AsyncStorage is for preferences and caches; credentials go in SecureStore; secrets such as raw card numbers are not stored at all.
  • A query cache combines freshness (staleTime) with request sharing; optimistic updates save, update, roll back on error and revalidate when settled.
  • List tuning is about stable keys, memoized rows, stable callbacks, fixed layouts and a sensible window. Measure first.

Next, get ready for questions about all of this in React Native Interview Questions.