Compose basics cheat sheet
Key ideas
- UI is a function of state: change the state and Compose redraws; never call
setTextorsetVisibility. - A
@Composablefunction returnsUnitand may run many times per second; keep the body cheap and free of side effects. - Recomposition is partial: only composables that read the changed state re-run; siblings with unchanged arguments are skipped.
- State flows down as parameters, events flow up as lambda callbacks; the composable that shows a value does not own it.
Modifierchains apply left-to-right, outermost-first;.padding().background()and.background().padding()produce different visuals.rememberstores a value across recompositions;rememberSaveablealso survives rotation and process death via saved instance state.LazyColumncomposes items on demand; always pass a stable, uniquekeyso state and animations follow the item, not the slot.MaterialThemeprovides a color scheme, typography and shapes throughCompositionLocals; children read them viaMaterialTheme.colorScheme,.typographyand.shapes.NavHostwith type-safe@Serializableroutes maps each route to a screen; navigate with an ID, never a domain object.- Side effects (network, listeners, logging) belong in
LaunchedEffect,DisposableEffect, or the ViewModel, never in the composable body.
APIs at a glance
| API or term | Use it for |
|---|---|
@Composable | Marks a function that emits UI into the composition; the runtime may call it many times or skip it. |
Modifier | Interface for chaining layout, drawing, and input modifiers; start from the empty Modifier and chain left-to-right. |
remember { } | Stores a value across recompositions at the same composition position; lost on rotation and process death. |
rememberSaveable { } | Like remember but also writes to saved instance state so the value survives rotation and process death. |
mutableStateOf / mutableIntStateOf | Creates observable state; reading .value in composition registers a reader, writing .value invalidates it. Use typed variants for Int, Long, Float, Double to avoid boxing. |
derivedStateOf | Computes a value from other state; wrap in remember; use when the result changes less often than its inputs. |
LazyColumn / LazyRow / LazyVerticalGrid | Lazy lists that compose items on demand; pass a unique key and optional contentType for mixed item types. |
MaterialTheme | Composable that provides colorScheme, typography and shapes to its children; wrap it in your app theme at the setContent root. |
NavHost / composable | Navigation container; type-safe routes via @Serializable classes; navigate with IDs, read back with toRoute<T>(). |
LaunchedEffect(key) | Launches a coroutine tied to a key; cancels the previous one when the key changes or the composable leaves composition. |
DisposableEffect | Registers and unregisters resources; must end with onDispose { }; use for lifecycle observers, listeners. |
rememberUpdatedState | Returns a State<T> that always holds the latest value; read it inside a long-running LaunchedEffect to avoid stale callbacks. |
Snippets
State hoisting: parent owns the value, child reports changes
@Composable
fun SearchScreen() {
var query by rememberSaveable { mutableStateOf("") }
Column {
OutlinedTextField(value = query, onValueChange = { query = it })
if (query.length > 2) {
Text("Results for: " + query)
}
Button(onClick = { query = "" }) { Text("Clear") }
}
}LazyColumn with stable keys and derivedStateOf for scroll threshold
data class Message(val id: Long, val text: String)
@Composable
fun MessageList(messages: List<Message>) {
val listState = rememberLazyListState()
val showJumpToTop by remember {
derivedStateOf { listState.firstVisibleItemIndex > 3 }
}
LazyColumn(state = listState) {
items(messages, key = { it.id }, contentType = { "message" }) { msg ->
var expanded by rememberSaveable { mutableStateOf(false) }
Card(onClick = { expanded = !expanded }, modifier = Modifier.animateItem()) {
Text(msg.text, maxLines = if (expanded) Int.MAX_VALUE else 2)
}
}
}
// showJumpToTop drives a "Jump to top" button, recomposing only when it flips
}LaunchedEffect with rememberUpdatedState to avoid stale callbacks
data class User(val name: String)
interface UserApi { suspend fun fetchUser(id: String): User }
@Composable
fun ProfileScreen(userId: String, api: UserApi, onProfileShown: (User) -> Unit) {
var profile by remember { mutableStateOf<User?>(null) }
val currentOnProfileShown by rememberUpdatedState(onProfileShown)
LaunchedEffect(userId) {
val user = api.fetchUser(userId)
profile = user
currentOnProfileShown(user)
}
Text(profile?.name ?: "Loading")
}AppTheme with dynamic color and a pre-Android 12 fallback
@Composable
fun AppTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
dynamicColor: Boolean = true,
content: @Composable () -> Unit,
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S ->
if (darkTheme) dynamicDarkColorScheme(LocalContext.current)
else dynamicLightColorScheme(LocalContext.current)
darkTheme -> darkColorScheme()
else -> lightColorScheme()
}
MaterialTheme(colorScheme = colorScheme, content = content)
}Rules of thumb
- Prefer changing state over calling UI update methods; Compose redraws only the composables that read the changed value.
- Never put side effects (network calls, logging, listener registration) in the composable body; use
LaunchedEffect,DisposableEffect, or the ViewModel. - Prefer
rememberSaveablefor small UI state that must survive rotation; userememberfor transient or expensive values that do not need to persist. - Never pass a domain object in a navigation route; pass an ID (
String,Int,Long) and load the object in the screen's ViewModel. - Prefer
derivedStateOf(wrapped inremember) when a high-frequency value is read only to check a threshold, not on every frame. - Never nest a vertically scrolling
LazyColumninsideModifier.verticalScroll; use one lazy list withitem { }blocks for extra content.
Gotchas
- Using var x = 0 inside a composable body. The value resets on every recomposition and Compose cannot observe it, so the UI never updates. Use
var x by remember { mutableIntStateOf(0) }instead. - Swapping .padding() and .background() order in a Modifier chain. Padding before background leaves a gap outside the painted area; padding after background indents the content inside it. Read the chain as outer-to-inner.
- Calling mutableStateOf outside remember. A new state object is created on every recomposition, so the value resets to its initial value each time. Wrap it in
remember { }; Android Lint flags this. - Navigating from LaunchedEffect(Unit) or from composition. The effect re-runs every time the screen re-enters composition, pushing the user forward again and breaking the back button. Navigate from click handlers or one-off events emitted by the ViewModel.
- Using MaterialTheme.colors (Material2 accessor) in a Material3 project. If the Material2 library is also on the classpath, the wrong import compiles but silently returns Material2 default colors. Use
androidx.compose.material3.MaterialTheme.colorScheme. - Omitting key on a LazyColumn that inserts, removes, or reorders items. Without a key, item identity is its position, so
rememberstate and animations belong to the wrong data item after any structural change. Pass a stable, unique key such as a database id.
Quick interview answers
Why does Compose call a @Composable function multiple times?
A composable is a function of state; whenever a state it reads changes, or its parent recomposes with different arguments, the runtime re-runs it. The body must be cheap and free of side effects because it can execute many times per second.
What is the difference between remember and rememberSaveable?
remember stores a value across recompositions at the same composition position but loses it on rotation or process death. rememberSaveable also writes the value to saved instance state so it survives those events, but the value must fit in a Bundle or you must supply a Saver.
How does state hoisting work in Compose?
The parent owns the state and passes the value down as a parameter; the child reports changes through a callback lambda such as onValueChange. The child must not wrap the incoming value in its own remember { mutableStateOf(...) }, or the two copies drift apart.
Why must you pass an ID, not a domain object, in a navigation route?
Domain objects need a custom NavType, bloat saved state (risking TransactionTooLargeException), and can show stale data. Pass a String, Int, or Long ID and load the object in the screen's ViewModel.
When should you use derivedStateOf?
Use it when a high-frequency input such as a scroll offset is read only to compute a threshold like 'show a button when index > 3'. It must be wrapped in remember; if the result changes as often as its inputs, just compute it directly in the body.
What happens if you put a network call in the composable body?
The body runs on every recomposition, so the call fires repeatedly and unpredictably. Move it into the ViewModel or wrap it in LaunchedEffect(key) so it runs only when the key changes.