Compose internals cheat sheet

Revise Compose internals: strong skipping, snapshot state, Modifier.Node, derivedStateOf, graphicsLayer, and compiler reports for Android interviews.

Key ideas

  1. Strong skipping is the default from Kotlin 2.0.20: unstable params compare with ===, stable params with equals; all restartable composables become skippable.
  2. A class with only val properties of stable types in a Compose-compiled module is inferred stable; no annotation needed.
  3. mutableStateOf(mutableListOf()) plus .add() does not trigger recomposition because the State is never written; use mutableStateListOf() or assign a new list.
  4. Read per-frame values inside graphicsLayer { } or offset { } to skip composition and layout and only redraw.
  5. derivedStateOf is for inputs that change more often than the result (e.g. scroll index threshold); remember(key) { } is for recompute-when-key-changes.
  6. Modifier.Node with LayoutModifierNode or DrawModifierNode replaces Modifier.composed { }; the element must implement equals and hashCode.
  7. AnimatedVisibility must not be wrapped in if; the exit animation never plays when the block leaves composition.
  8. A LazyColumn inside a vertically scrolling Column throws because it receives an infinite max height; use one lazy list with multiple item blocks.
  9. Compose compiler reports are plain text, CSV, and JSON (classes.txt, composables.txt, composables.csv, module.json); there is no HTML report.
  10. snapshotFlow emits only distinct results and may skip intermediate values if several writes happen before it runs again.

APIs at a glance

API or termUse it for
mutableStateOfsnapshot state that invalidates readers on write; default policy is structuralEqualityPolicy()
mutableStateListOfsnapshot list that notifies on .add(), .remove(), etc., unlike a plain list inside mutableStateOf
derivedStateOfcached 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.Noderecommended base for custom modifiers; combine LayoutModifierNode and DrawModifierNode as needed
Layout(content, modifier) { }basic custom layout; Row, Column, and Box are built on it
updateTransitionkeep several animated properties on one timeline; give each animation a label for Animation Preview
Animatableimperative 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) { } over derivedStateOf when the result changes as often as the input.
  • Never wrap AnimatedVisibility in an if; pass the condition as visible so the exit animation can play.
  • Prefer graphicsLayer { } or offset { } lambda forms for per-frame values to skip composition and layout.
  • Never measure a Measurable twice in one pass; use intrinsics or SubcomposeLayout when a child's size drives another's constraints.
  • Prefer Modifier.Node over Modifier.composed { } for custom modifiers; the element must be a data class or implement equals/hashCode.
  • Never nest a LazyColumn inside a vertically scrolling Column; put all content into one lazy list with multiple item and items blocks.

Gotchas

  • Mutating a list inside mutableStateOf with .add(). The State object is never written, so no reader is invalidated and the UI stays stale. Use mutableStateListOf() 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 equals on 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 Animatable with the initial value is created on each recomposition, so the animation keeps restarting. Wrap it in remember { Animatable(0f) }.
  • Reading firstVisibleItemScrollOffset in the composable body. It recomposes on every scrolled pixel. Read it inside offset { } or graphicsLayer { }, or wrap a threshold in derivedStateOf.
  • 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 var or 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.

Go deeper