Navigation in Compose
Why it matters
- Every multi-screen app needs a navigation graph; getting it wrong causes crashes, lost back-stack state, or screens that open twice.
- Interviewers ask you to draw a nav graph, explain what happens on
popBackStack, and describe why you pass an ID instead of a domain object into a route. - Type-safe routes with
@Serializable(Navigation Compose 2.8+) replace fragile string paths and catch route typos at compile time. - Misunderstanding when a
composabledestination enters and leaves composition leads to cancelled work, repeated side effects and duplicate network calls.
The simple explanation
- A
NavHostis a single stage that shows one screen at a time. - Each
composableblock is a curtain for one act; only the active curtain is visible. - The back stack is a stack of index cards;
popBackStackremoves the top card and shows the one below. - A route is the address written on the card, not the actor standing on stage.
- Passing an ID is like writing "room 42" on the card instead of taping the whole room's furniture to it.
A NavHost is a single composable that owns a back stack of back stack entries. Each entry points to a destination registered inside the host via a composable block. Only the top entry is composed (two entries during a transition animation). Entries below it stay on the stack with their saved state and ViewModels, but their UI is not composed.
String-based routes (long-standing API) use a path like "detail/{id}". You read the parameter with backStackEntry.arguments?.getString("id"). This works but is error-prone: a typo or a type mismatch in the path string only fails at runtime.
Type-safe routes (Navigation Compose 2.8.0+, stable) replace the path with a @Serializable class or object. It does not implement any Navigation interface:
| Concept | String-based | Type-safe |
|---|---|---|
| Route definition | "detail/{id}" | @Serializable data class Detail(val id: String) |
| Register destination | composable("detail/{id}") | composable<Detail> |
| Navigate | navigate("detail/$id") | navigate(Detail(id)) |
| Read param | backStackEntry.arguments?.getString("id") | backStackEntry.toRoute<Detail>().id |
Key rules:
- Pass IDs, not objects. Route fields are stored as arguments in the back stack's saved state. A domain object cannot go there without a custom
NavType, bloats saved state, and becomes a stale copy of data that has a real source (repository or database). NavHostis stateless. It reads the back stack from theNavControllerand renders the top entry. It does not own screen state.- A destination is composed only while it is shown. When you navigate forward, the previous screen leaves composition: its
LaunchedEffects are cancelled and plainrememberstate is dropped, whilerememberSaveablestate is saved for that entry and restored when you come back. rememberNavController()creates a controller whose back stack is saved withrememberSaveable, so it survives configuration changes and process death.
Notes
NavHosttakes aNavControllerand astartDestination. It composes only the top back-stack entry (plus the outgoing one during a transition).- A
composabledestination's content runs only while that entry is shown. Navigating forward or popping removes it from composition and cancels anyLaunchedEffectinside it. - With type-safe routes, each route is a
@Serializableclass or object. You navigate withnavController.navigate(Detail("42"))and read it back withbackStackEntry.toRoute<Detail>(), or in a ViewModel withsavedStateHandle.toRoute<Detail>(). - Always pass an ID (a
String,IntorLong) in the route, never a domain object. Primitives, strings and enums work out of the box; any other type needs a customNavTypeintypeMap, which is a sign you are passing too much. rememberNavController()saves the back stack withrememberSaveable, so it survives rotation and process death. A controller created with plainrememberis lost on rotation.navController.popBackStack()removes the top entry and shows the one below.popBackStack<Home>(inclusive = true)pops up to and includingHome;inclusive = falsestops just before it.navController.currentBackStackEntryAsState()gives you aStateof the current entry. Use it to highlight the selected bottom-nav item; only composables that read it recompose when the destination changes.- Route fields become the destination's arguments automatically. You do not declare a separate
argumentslist with type-safe routes. - Nested graphs (
navigation<Graph>(startDestination = ...)blocks) group screens, such as a sign-in flow, inside the sameNavHost. Entries in a nested graph can share a ViewModel scoped to the graph's back-stack entry. navigateis an event. Call it from a click handler or from a one-off event, not from composition. ALaunchedEffect(Unit) { navigate(...) }runs again every time the screen re-enters composition, for example when the user comes back to it.
Code example
This shows a two-screen graph with type-safe routes: a list screen navigates to a detail screen by passing an ID, and the detail screen pops back on a back-press.
import androidx.compose.runtime.Composable
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.toRoute
import kotlinx.serialization.Serializable
// Route classes: serializable, carry only IDs
@Serializable
data class Home(val tab: Int = 0)
@Serializable
data class Detail(val itemId: String)
@Composable
fun AppNavHost(navController: NavHostController = rememberNavController()) {
NavHost(
navController = navController,
startDestination = Home()
) {
// List screen
composable<Home> { backStackEntry ->
val route = backStackEntry.toRoute<Home>()
HomeScreen(
tab = route.tab,
onItemClicked = { id ->
// Pass the ID, not the whole item object
navController.navigate(Detail(id))
}
)
}
// Detail screen
composable<Detail> { backStackEntry ->
val route = backStackEntry.toRoute<Detail>()
DetailScreen(
itemId = route.itemId,
onBack = { navController.popBackStack() }
)
}
}
}HomeandDetailare plain@Serializabledata classes. The Kotlin serialization plugin must be applied, and every field type needs a serializer, so a field likeContextorBitmapfails at build time.rememberNavController()is used so the back stack is saved and restored across rotation and process death.navController.navigate(Detail(id))passes only aStringID. The detail screen loads the full object from a repository, so the route stays small and the data has one source of truth.navController.popBackStack()with no arguments removes only the top entry, returning toHome. UsepopBackStack<Home>(inclusive = false)to jump back to a specific destination from deeper in the stack.- The system back button and predictive back pop the stack automatically;
onBackis only for an on-screen back arrow.
Run the idea in plain Kotlin
fun main() {
// Simulating navigation logic without Android dependencies
val backStack = mutableListOf<String>()
// 1. Start at Home
backStack.add("Home")
println("Start: " + backStack.joinToString(" -> "))
// 2. Navigate to Detail with ID "42"
backStack.add("Detail(42)")
println("Navigate to Detail: " + backStack.joinToString(" -> "))
// 3. Pop back
backStack.removeAt(backStack.lastIndex)
println("Pop back: " + backStack.joinToString(" -> "))
// 4. Verify current destination
val current = backStack.last()
println("Current destination is: " + current)
// 5. Check if we are at Home
if (current == "Home") {
println("Success: We are back at Home")
} else {
println("Error: We are not at Home")
}
}Expected output:
Start: Home
Navigate to Detail: Home -> Detail(42)
Pop back: Home
Current destination is: Home
Success: We are back at Home
In production
- Crash reports showed
TransactionTooLargeException(often wrapped in aRuntimeException) when users left the app from a product detail screen. It never happened in quick QA runs. - The route was
data class Detail(val product: Product). The team had madeProductserializable and registered a customNavTypethat stored it as JSON. - Some products had long descriptions and dozens of review snippets. When the activity saved its state, the back stack carried every product the user had opened, and the saved state went over the Binder transaction limit (about 1 MB, shared by the whole transaction).
- Reproduced by opening several large products, then pressing Home. The crash appeared when the activity saved its state.
- Changed the route to
data class Detail(val productId: String)and removed the customNavType. The detail ViewModel reads the id withsavedStateHandle.toRoute<Detail>()and loads the product from the repository. - Added a test that round-trips every route class through kotlinx.serialization and asserts routes contain only ids and small values.
- The crash stopped, and the detail screen now shows fresh data instead of the copy captured at navigation time.
- Dashboards showed about twice as many calls to the product-detail endpoint as screen views.
- The detail screen started loading with
LaunchedEffect(Unit) { viewModel.load(itemId) }. - Every time the user opened a sub-screen (reviews, photos) and came back, the detail destination re-entered composition and the effect ran again. Rotation did the same.
- Reproduced by opening a detail screen, opening reviews, and pressing back while watching the network log.
- Moved loading into the ViewModel: it reads
itemIdfromSavedStateHandlewithtoRoute<Detail>()and starts loading ininit. The ViewModel is scoped to the back-stack entry, so it survives leaving composition and rotation, and loads once per entry. - The screen now only collects
uiStatefrom the ViewModel. - Added a test that navigates to the sub-screen and back and asserts the repository was called once.
Common mistakes
- Passing a domain object in the route. It needs a custom
NavType, bloats saved state (riskingTransactionTooLargeException) and shows stale data. Pass an ID and load the object in the screen's ViewModel. - Creating the controller with plain
remember. The back stack is not saved, so after rotation or process death the user is thrown back to the start destination. UserememberNavController(). - Navigating from composition or from a
LaunchedEffect(Unit). The effect runs again whenever the screen re-enters composition, so the user is pushed forward again and cannot go back. Navigate from event handlers, or from a one-off event emitted by the ViewModel. - Using string routes with string concatenation for parameters.
navigate("detail/$id")is matched at runtime. A typo or a missing{id}placeholder fails only when you navigate. Type-safe routes with@Serializablecatch these at compile time. - Reading navController.currentDestination in a composable instead of currentBackStackEntryAsState().
currentDestinationis a plain property; reading it does not register a state read, so the composable will not recompose when the destination changes. UsecurrentBackStackEntryAsState().value?.destination. - Starting long work in a screen's
LaunchedEffect. It is cancelled as soon as the screen leaves composition, which also happens when you navigate forward, not only when you pop. Put work that must finish in the ViewModel (viewModelScope) or, if it must outlive the screen, in WorkManager. - Forgetting the serialization plugin. Without
org.jetbrains.kotlin.plugin.serialization, the@Serializableannotation still compiles but no serializer is generated, and navigation fails at runtime.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What is a NavHost and how does it relate to the back stack?”
“Why should you pass an ID in a route instead of the full object?”
“What happens to a LaunchedEffect inside a destination when the user navigates?”
“How do type-safe routes differ from string-based routes, and when would you still use strings?”
Quiz
What does rememberNavController() do that remember { NavHostController() } does not?
A route is defined as @Serializable data class Detail(val item: Product), where Product is a plain class holding a Bitmap. What is the likely result?
What happens to a LaunchedEffect inside a composable block when that destination is popped from the back stack?
With type-safe routes, what is the idiomatic way to read itemId inside the composable block for the Detail route?
0 of 4 answered
Mini task
Build a two-screen navigation graph
-
Create a new Compose project (or open an existing one) and add the Navigation Compose dependency
androidx.navigation:navigation-compose(2.8.0 or newer) plus the Kotlin serialization plugin (org.jetbrains.kotlin.plugin.serialization) and thekotlinx-serialization-jsonlibrary. -
Define two route classes at the top level:
@Serializable data class Home(val tab: Int = 0)@Serializable data class Detail(val itemId: String)
-
Create a
NavHostwithrememberNavController()andstartDestination = Home(). -
Register two
composableblocks: one forHomethat shows aLazyColumnof item IDs, and one forDetailthat shows theitemIdtext and a back button. -
In the
Homeblock, callnavController.navigate(Detail(id))when an item is clicked. In theDetailblock, callnavController.popBackStack()on the back button. -
Rotate the device on the detail screen. Confirm the back stack is preserved (you land back on the detail screen, not the home screen).
-
Enable "Don't keep activities" in developer options, put the app in the background on the detail screen, and return. Confirm you are still on the same detail item.
Done condition: You can navigate from Home to Detail, press back to return, and rotate or recreate the activity on the Detail screen without losing the stack or the item id.