Navigation and state management

Learn React Native navigation and state management: React Navigation stacks, typed params, Zustand, Redux Toolkit and TanStack Query, compared with Android. About 25 minutes.

Why it matters

  • Every React Native app needs a navigation library and a state strategy, and the choices map closely to what you know from Android: Navigation Compose back stacks, ViewModels, and a repository with a cache.
  • Putting each piece of state in the right place (component, client store or server cache) avoids most re-render problems and most stale data bugs.
  • Interviewers ask you to separate local UI state, global client state and server state, and to say which tool fits each. "Put it all in Redux" is the answer that loses points.
  • Android adds requirements that iOS-first code often misses: the system back button and gesture, deep links into the right screen, and screens that must survive process death.

The simple explanation

  • A navigation stack is the Android back stack: new screens go on top, back pops the top one.
  • Local state is like remember in a composable: it belongs to one screen element and disappears with it.
  • A global store such as Zustand is like a singleton state holder exposing a StateFlow that many screens collect.
  • TanStack Query is like a repository with an in-memory cache: it fetches, caches by key, refetches when data is marked stale, and tracks loading and error for you.

How do navigation and state management work in React Native? Navigation is a JavaScript library, most often React Navigation, which provides stack, tab and drawer navigators. Its native stack navigator (createNativeStackNavigator) uses the platform's native screen primitives through react-native-screens. Expo Router is a file-based router built on top of React Navigation, where each file in the app folder becomes a route. State management is split by where the data comes from:

  1. Local state: useState or useReducer inside a component. It is lost when the component unmounts.
  2. Global client state: data the app owns and many screens read, such as the signed-in user, theme or a draft cart. Context works for values that rarely change; Zustand and Redux Toolkit are the common stores.
  3. Server state: data that lives on a backend and that you only hold a copy of. TanStack Query (formerly React Query) caches it by query key and handles loading, errors, refetching and invalidation. Redux Toolkit has its own equivalent, RTK Query.

Navigation basics. In React Navigation 7, navigation.navigate('Details') pushes Details unless it is already the focused screen, navigation.push('Details') always adds a new entry, navigation.goBack() pops one, and navigation.popTo('Home') goes back to an existing screen. Screens below the top of a stack stay mounted, so their state survives, much like back stack entries in Navigation Compose. React Navigation handles the Android back button for you: the focused navigator pops a screen if it can, otherwise the press goes to its parent navigator, and if no navigator can go back, the system handles it and the user leaves the app.

Typed routes. You describe each screen's params in a TypeScript type (Account: { accountId: string }), so navigate('Account') without the param fails to compile. It is the same goal as type-safe routes with @Serializable classes in Navigation Compose. Params should be small and serializable (IDs, not whole objects), because navigation state can be persisted and restored, and deep links can only carry strings.

State typeTypical toolLives untilAndroid analogyExample
LocaluseState, useReducerComponent unmountsremember / rememberSaveableText field value, toggle
Global clientContext, Zustand, Redux ToolkitApp process ends (unless persisted)Shared state holder with StateFlowAuth session, theme, cart
ServerTanStack Query, RTK QueryCache entry is garbage collectedRepository with a cacheProfile, product list, balance
NavigationReact Navigation, Expo RouterScreen is poppedNavigation back stackCurrent screen and its params

Notes

  • React Navigation offers a static configuration API (screens declared as an object, with types inferred) and a dynamic one (Stack.Navigator and Stack.Screen components inside a NavigationContainer). Both are supported; the docs show both for each feature.
  • createNativeStackNavigator uses the platform's native screen containers through react-native-screens. The JavaScript-based createStackNavigator is more customisable but does its animations in JS.
  • Since React Navigation 7, navigate no longer goes back to an existing screen in the stack; use popTo for that, or push to add the same screen again.
  • Screens under the top of a stack stay mounted. Use useFocusEffect (or useIsFocused) to run work when a screen gains focus, the way you might react to Lifecycle.State.RESUMED on Android.
  • For a custom overlay that is not a screen, use React Native's Modal and handle onRequestClose, which Android calls on a back press, or listen with BackHandler. A plain absolutely positioned View ignores the back button.
  • Deep links are configured with the linking prop on NavigationContainer (or automatically from file names in Expo Router), and still need the intent filters in the Android manifest.
  • For auth flows, React Navigation recommends rendering different screens based on the signed-in state, so the login screen is not left on the back stack after sign-in.
  • Context re-renders every component that reads it whenever its value changes. Use it for rarely changing values; use a store with selectors for frequently changing state.
  • In Zustand, read with a selector such as useAuthStore((s) => s.token) so the component re-renders only when that slice changes. A selector that returns a new object every time needs useShallow.
  • Redux Toolkit is the official way to write Redux: configureStore and createSlice replace hand-written action types and reducers, and Immer lets reducers write "mutating" code safely.
  • In TanStack Query, the query key identifies the data (['account', id]). After a mutation, call queryClient.invalidateQueries({ queryKey: ['account', id] }) to mark it stale and refetch active queries.
  • A state setter does not change the variable in the current render; the new value appears on the next render. Do not read state right after setting it.

Code example

A typed native stack with an auth flow from a Zustand store, and an account screen whose balance comes from TanStack Query and is refreshed after a transfer.

import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import type { NativeStackScreenProps } from '@react-navigation/native-stack';
import {
  QueryClient,
  QueryClientProvider,
  useMutation,
  useQuery,
  useQueryClient,
} from '@tanstack/react-query';
import { Button, Text, View } from 'react-native';
import { create } from 'zustand';
 
// Typed routes: params per screen, like type-safe routes in Navigation Compose
type RootStackParamList = {
  Login: undefined;
  Home: undefined;
  Account: { accountId: string };
};
 
// Global client state (Zustand)
type AuthState = {
  token: string | null;
  signIn: (token: string) => void;
  signOut: () => void;
};
 
export const useAuthStore = create<AuthState>()((set) => ({
  token: null,
  signIn: (token) => set({ token }),
  signOut: () => set({ token: null }),
}));
 
// Server state (TanStack Query)
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 (await res.json()) as Account;
}
 
async function postTransfer(accountId: string, amount: number): Promise<void> {
  const res = await fetch(`https://api.example.com/accounts/${accountId}/transfers`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ amount }),
  });
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
}
 
const Stack = createNativeStackNavigator<RootStackParamList>();
const queryClient = new QueryClient();
 
function LoginScreen() {
  const signIn = useAuthStore((s) => s.signIn); // selector: re-render only if this changes
  return <Button title="Sign in" onPress={() => signIn('demo-token')} />;
}
 
function HomeScreen({ navigation }: NativeStackScreenProps<RootStackParamList, 'Home'>) {
  const signOut = useAuthStore((s) => s.signOut);
  return (
    <View>
      <Button
        title="Open account"
        onPress={() => navigation.navigate('Account', { accountId: 'a1' })}
      />
      <Button title="Sign out" onPress={signOut} />
    </View>
  );
}
 
function AccountScreen({ route }: NativeStackScreenProps<RootStackParamList, 'Account'>) {
  const { accountId } = route.params;
  const client = useQueryClient();
 
  const account = useQuery({
    queryKey: ['account', accountId],
    queryFn: ({ signal }) => fetchAccount(accountId, signal), // cancelled if no longer needed
  });
 
  const transfer = useMutation({
    mutationFn: (amount: number) => postTransfer(accountId, amount),
    // mark the balance stale and refetch it; returning the promise keeps the mutation pending until then
    onSuccess: () => client.invalidateQueries({ queryKey: ['account', accountId] }),
  });
 
  if (account.isPending) return <Text>Loading…</Text>;
  if (account.isError) return <Text>Error: {account.error.message}</Text>;
 
  return (
    <View>
      <Text>Balance: {account.data.balance}</Text>
      <Button
        title="Send 10"
        disabled={transfer.isPending}
        onPress={() => transfer.mutate(10)}
      />
    </View>
  );
}
 
export default function App() {
  const isSignedIn = useAuthStore((s) => s.token !== null);
  return (
    <QueryClientProvider client={queryClient}>
      <NavigationContainer>
        <Stack.Navigator>
          {isSignedIn ? (
            <>
              <Stack.Screen name="Home" component={HomeScreen} />
              <Stack.Screen name="Account" component={AccountScreen} />
            </>
          ) : (
            <Stack.Screen name="Login" component={LoginScreen} />
          )}
        </Stack.Navigator>
      </NavigationContainer>
    </QueryClientProvider>
  );
}
  • RootStackParamList makes navigation.navigate('Account', { accountId: 'a1' }) type-checked: leaving out accountId or misspelling the screen name is a compile error.
  • The navigator renders different screens depending on isSignedIn. Signing in or out swaps the screens, so back from Home cannot return to Login, which is the auth pattern React Navigation recommends.
  • The balance is never copied into a store. TanStack Query owns it under the key ['account', accountId], and invalidateQueries after the mutation refetches it.

Run the idea in plain Kotlin

This models a stack navigator's navigate, push, popTo and back handling, and a query cache that only refetches after the key is invalidated.

data class Route(val name: String, val params: Map<String, String> = emptyMap())

class StackNavigator(initial: Route) {
  private val routes = mutableListOf(initial)

  // navigate: stay if that screen is focused (updating params), otherwise push
  fun navigate(route: Route) {
      if (routes.last().name == route.name) routes[routes.lastIndex] = route else routes.add(route)
  }

  fun push(route: Route) {
      routes.add(route)
  }

  // popTo: go back to an existing screen
  fun popTo(name: String) {
      val index = routes.indexOfLast { it.name == name }
      if (index >= 0) {
          while (routes.size > index + 1) routes.removeAt(routes.lastIndex)
      } else {
          routes[routes.lastIndex] = Route(name)
      }
  }

  // Android back: pop if possible, otherwise let the system handle it
  fun onBackPressed(): Boolean {
      if (routes.size <= 1) return false
      routes.removeAt(routes.lastIndex)
      return true
  }

  fun describe(): String = routes.joinToString(" > ") { it.name }
}

class QueryCache(private val fetcher: (String) -> Int) {
  private val data = mutableMapOf<String, Int>()
  private val stale = mutableSetOf<String>()
  var fetchCount = 0
      private set

  // Simplified: TanStack Query also shows cached data while it refetches in the background
  fun get(key: String): Int {
      if (key !in data || key in stale) {
          data[key] = fetcher(key)
          stale.remove(key)
          fetchCount++
      }
      return data.getValue(key)
  }

  fun invalidate(key: String) {
      stale.add(key)
  }
}

fun main() {
  val nav = StackNavigator(Route("Home"))
  nav.navigate(Route("Account", mapOf("accountId" to "a1")))
  println("navigate: " + nav.describe())
  nav.navigate(Route("Account", mapOf("accountId" to "a1")))
  println("navigate again: " + nav.describe())
  nav.push(Route("Account", mapOf("accountId" to "a2")))
  println("push: " + nav.describe())
  nav.navigate(Route("Settings"))
  println("navigate: " + nav.describe())
  nav.popTo("Home")
  println("popTo Home: " + nav.describe())
  println("back handled by navigator: " + nav.onBackPressed())

  var serverBalance = 100
  val cache = QueryCache { serverBalance }
  println("balance " + cache.get("account:a1") + ", fetches " + cache.fetchCount)
  println("balance " + cache.get("account:a1") + ", fetches " + cache.fetchCount)
  serverBalance = 90 // a transfer succeeded on the server
  println("before invalidate: " + cache.get("account:a1"))
  cache.invalidate("account:a1")
  println("after invalidate: " + cache.get("account:a1") + ", fetches " + cache.fetchCount)
}

Expected output:

navigate: Home > Account
navigate again: Home > Account
push: Home > Account > Account
navigate: Home > Account > Account > Settings
popTo Home: Home
back handled by navigator: false
balance 100, fetches 1
balance 100, fetches 1
before invalidate: 100
after invalidate: 90, fetches 2

In production

Android back button closes the app from a custom sheet
  • Android users reported that pressing back while a filter sheet was open closed the whole app instead of closing the sheet.
  • The sheet was an absolutely positioned View shown with a boolean in state. It was not a screen and did not handle the back press, so the press went to the navigator, which was already on its first screen, and the system left the app.
  • iOS has no back button, so the bug never appeared during iOS-first testing.
The fix
  • The team moved the sheet into the stack as a screen with presentation: 'modal', so back pops it like any other screen and it gets a deep link for free.
  • Simpler overlays that stayed outside navigation used React Native's Modal with onRequestClose, which Android calls on a back press.
  • They added an Android back-button step to the release test checklist.
Stale balance after a transfer
  • Users saw their old balance after completing a transfer until they restarted the app.
  • The balance was fetched once in a useEffect and copied into a global store. Nothing refetched it after the transfer, and each screen read the copy.
The fix
  • The team moved the balance to TanStack Query under the key ['account', id] and removed it from the store.
  • The transfer became a useMutation whose onSuccess calls queryClient.invalidateQueries({ queryKey: ['account', id] }), so every screen showing the balance refetches.
  • The store kept only client state (the session and UI preferences).

Common mistakes

  • Copying server data into Redux or Zustand. You then own caching, refetching and invalidation by hand, and copies drift apart. Keep server data in TanStack Query or RTK Query and keep stores for client state.
  • Reading the whole store. const state = useStore() re-renders the component on every change to any field. Select only what you need, and wrap selectors that return new objects in useShallow.
  • Mutating state in place. state.user.name = 'Bob' keeps the same reference, so React and Zustand selectors see no change and nothing re-renders. Create a new object; Redux Toolkit reducers are the exception because Immer handles it.
  • Passing whole objects as navigation params. Large or non-serializable params break state persistence and deep links and go stale when the data changes. Pass an ID and load the data on the screen.
  • Using navigate to go back. Since React Navigation 7, navigate to a screen lower in the stack pushes a new copy. Use goBack or popTo.
  • Untyped navigation. Calling navigate('Acount') with a typo fails only at runtime. Define a param list type and use it with the navigator and screen props.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“How do you decide where a piece of state lives in a React Native app?”

“How does React Navigation handle the Android back button?”

“Why use TanStack Query instead of fetching data in a useEffect?”

“What makes a global store slow in React Native, and how do you fix it?”

Quiz

Which tool is designed to cache data fetched from a REST API and refetch it when it becomes stale?

In a React Navigation native stack, what happens to the current screen when you push a new screen on top?

A component reads const state = useAuthStore() from a Zustand store but only shows the user's name. What is the problem?

After a successful transfer mutation, how do you refresh the account balance cached by TanStack Query?

0 of 4 answered

Mini task

Task: Build a typed auth flow with server data

  1. Create a Zustand store useAuthStore with token: string | null, signIn(token) and signOut(), using create<AuthState>()(...).
  2. Define RootStackParamList with Login, Home and Profile: { userId: string }, and create a native stack with createNativeStackNavigator<RootStackParamList>().
  3. Render Login when token is null and Home plus Profile otherwise. Read the token with a selector.
  4. In Profile, load the user with useQuery({ queryKey: ['user', userId], queryFn }) from any public test API, and show loading and error states.
  5. Add a "Refresh" button that calls queryClient.invalidateQueries({ queryKey: ['user', userId] }).
  6. On an Android emulator, press back on Home and on Profile and note what happens in each case.

Done when: signing in replaces the login screen without leaving it on the back stack, navigate('Profile') without userId fails to compile, back from Profile returns to Home, back from Home leaves the app, and Refresh triggers a new request.

Next: Native modules and the New Architecture