Compose internals cheat sheet
Key ideas
- Strong skipping is the default from Kotlin 2.0.20: unstable params compare with
===, stable params withequals; all restartable composables become skippable. - A class with only
valproperties of stable types in a Compose-compiled module is inferred stable; no annotation needed. mutableStateOf(mutableListOf())plus.add()does not trigger recomposition because theStateis never written; usemutableStateListOf()or assign a new list.- Read per-frame values inside
graphicsLayer { }oroffset { }to skip composition and layout and only redraw. derivedStateOfis for inputs that change more often than the result (e.g. scroll index threshold);remember(key) { }is for recompute-when-key-changes.Modifier.NodewithLayoutModifierNodeorDrawModifierNodereplacesModifier.composed { }; the element must implementequalsandhashCode.AnimatedVisibilitymust not be wrapped inif; the exit animation never plays when the block leaves composition.- A
LazyColumninside a vertically scrollingColumnthrows because it receives an infinite max height; use one lazy list with multipleitemblocks. - Compose compiler reports are plain text, CSV, and JSON (
classes.txt,composables.txt,composables.csv,module.json); there is no HTML report. snapshotFlowemits only distinct results and may skip intermediate values if several writes happen before it runs again.
APIs at a glance
| API or term | Use it for |
|---|---|
mutableStateOf | snapshot state that invalidates readers on write; default policy is structuralEqualityPolicy() |
mutableStateListOf | snapshot list that notifies on .add(), .remove(), etc., unlike a plain list inside mutableStateOf |
derivedStateOf | cached computed value when the input changes far more often than the result you need |
remember(key) { } | recompute a value only when the key changes; preferred over derivedStateOf when result changes as often as input |
graphicsLayer { } | read animated values in the draw phase, skipping composition and layout |
Modifier.Node | recommended base for custom modifiers; combine LayoutModifierNode and DrawModifierNode as needed |
Layout(content, modifier) { } | basic custom layout; Row, Column, and Box are built on it |
updateTransition | keep several animated properties on one timeline; give each animation a label for Animation Preview |
Animatable | imperative animation with snapTo, animateTo, and fling velocity; wrap in remember |
composeCompiler { } | Gradle block for compiler reports (reportsDestination) and stabilityConfigurationFiles |
Snippets
Cache a filtered list so the child skips on unrelated recompositions
data class User(val name: String)
@Composable
fun UserList(users: List<User>) {
LazyColumn { items(users) { Text(it.name) } }
}
@Composable
fun SearchScreen(allUsers: List<User>) {
var query by remember { mutableStateOf("") }
var clicks by remember { mutableIntStateOf(0) }
val filtered = remember(allUsers, query) {
allUsers.filter { it.name.contains(query, ignoreCase = true) }
}
Column {
TextField(value = query, onValueChange = { query = it })
Button(onClick = { clicks++ }) { Text("Click") }
Text("Clicks: $clicks")
UserList(filtered) // same instance when only clicks changed -> skipped
}
}Custom modifier via Modifier.Node (replaces Modifier.composed)
private data class UniformPaddingElement(val all: Dp) : ModifierNodeElement<UniformPaddingNode>() {
override fun create() = UniformPaddingNode(all)
override fun update(node: UniformPaddingNode) { node.all = all }
}
private class UniformPaddingNode(var all: Dp) : Modifier.Node(), LayoutModifierNode {
override fun MeasureScope.measure(measurable: Measurable, constraints: Constraints): MeasureResult {
val pad = all.roundToPx()
val p = measurable.measure(constraints.offset(-pad * 2, -pad * 2))
val w = (p.width + pad * 2).coerceIn(constraints.minWidth, constraints.maxWidth)
val h = (p.height + pad * 2).coerceIn(constraints.minHeight, constraints.maxHeight)
return layout(w, h) { p.placeRelative(pad, pad) }
}
}
fun Modifier.uniformPadding(all: Dp): Modifier = this then UniformPaddingElement(all)Deferred reads: pass a lambda so the child reads scroll state in its own phase
@Composable
fun CollapsingHeader(listState: LazyListState) {
val headerScroll = {
if (listState.firstVisibleItemIndex == 0)
listState.firstVisibleItemScrollOffset else Int.MAX_VALUE
}
Box(
Modifier.fillMaxWidth().height(200.dp)
.offset { IntOffset(0, -(headerScroll().coerceAtMost(200.dp.roundToPx()) / 2)) }
.graphicsLayer { alpha = 1f - (headerScroll() / 200.dp.toPx()).coerceIn(0f, 1f) }
.background(Color(0xFF3F51B5))
)
}Rules of thumb
- Prefer
remember(key) { }overderivedStateOfwhen the result changes as often as the input. - Never wrap
AnimatedVisibilityin anif; pass the condition asvisibleso the exit animation can play. - Prefer
graphicsLayer { }oroffset { }lambda forms for per-frame values to skip composition and layout. - Never measure a
Measurabletwice in one pass; use intrinsics orSubcomposeLayoutwhen a child's size drives another's constraints. - Prefer
Modifier.NodeoverModifier.composed { }for custom modifiers; the element must be adata classor implementequals/hashCode. - Never nest a
LazyColumninside a vertically scrollingColumn; put all content into one lazy list with multipleitemanditemsblocks.
Gotchas
- Mutating a list inside mutableStateOf with .add(). The
Stateobject is never written, so no reader is invalidated and the UI stays stale. UsemutableStateListOf()or assign a new list (items = items + item). - Allocating collections in the composable body (filter, map, sortedBy). A new instance is created on every recomposition, so a child taking that list never skips. Move the work to the ViewModel or
remember(key) { }. - Using ImmutableList everywhere as a reflex. Compose compares every element with
equalson each recomposition, which can cost more than a recomposition in big lists. Prefer preserving the same instance and measure before forcing structural comparison. - Creating Animatable without remember. A new
Animatablewith the initial value is created on each recomposition, so the animation keeps restarting. Wrap it inremember { Animatable(0f) }. - Reading firstVisibleItemScrollOffset in the composable body. It recomposes on every scrolled pixel. Read it inside
offset { }orgraphicsLayer { }, or wrap a threshold inderivedStateOf. - Listing a mutable class in the stability configuration file. Compose may skip a composable whose data actually changed, showing stale UI. Only list classes that are truly immutable; a
varor mutable collection makes the promise unsafe.
Quick interview answers
What is strong skipping and when did it become the default?
Strong skipping became the default from Kotlin 2.0.20. Under it, unstable parameters are compared with === and stable parameters with equals, and every restartable composable becomes skippable.
Why does mutableStateOf(mutableListOf()) plus .add() not trigger recomposition?
The State object itself is never written; only the internal list is mutated, so Compose has no signal to invalidate readers. Use mutableStateListOf() or assign a new list such as items = items + item.
When should you use derivedStateOf versus remember(key) { }?
Use derivedStateOf when the input changes far more often than the result you need, such as a scroll-index threshold that flips a Boolean. Use remember(key) { } when you want to recompute a value only when a specific key changes, like a filtered list.
Why must you not wrap AnimatedVisibility in an if?
When the condition turns false the entire block leaves composition at once, so the exit animation never plays. Pass the condition as the visible parameter and keep the composable in the tree.
What is the difference between Modifier.composed { } and Modifier.Node?
Modifier.composed { } runs composition work for every element it is used on and cannot be skipped like a node. Modifier.Node with LayoutModifierNode or DrawModifierNode is the recommended approach; the element must implement equals and hashCode so Compose knows when update() is needed.
How do you verify recomposition and skip counts in a real app?
Use Layout Inspector to see recomposition and skip counts at runtime. For compile-time stability decisions, read the composables.txt report generated by the composeCompiler Gradle block, which marks each function restartable/skippable and each parameter stable/unstable.