Why does this Compose LazyColumn recompose the whole screen on scroll?
Question
A Jetpack Compose feed renders 100 messages in a LazyColumn (10 visible at once) and shows a "Back to top" button once you scroll past item 0:
@Composable
fun FeedScreen(messages: List<Msg>, onSelect: (Long) -> Unit) {
val listState = rememberLazyListState()
val showTop = listState.firstVisibleItemIndex > 0
Box {
LazyColumn(state = listState) {
items(messages) { msg -> MsgRow(msg, onSelect) }
}
if (showTop) TopButton()
}
}Scrolling across 15 items recomposes FeedScreen 15 times instead of once. Prepending 1 new message also moves an expanded row's remember toggle onto the wrong message and recomposes all 10 visible rows.
- Explain both bugs.
- Fix the composable and explain how parameter stability lets Compose skip unchanged rows.
Show hints (3)
- "CHECK SNAPSHOT READS"
Reading
listState.firstVisibleItemIndexdirectly inFeedScreensubscribes the whole composable to every scroll index tick, even whenshowTopstaystrue. - "FILTER BOOLEAN CHANGES"
Wrap the boolean expression in
remember { derivedStateOf { ... } }soFeedScreenonly recomposes whenshowTopflips betweenfalseandtrue. - "KEY LAZY ITEMS"
Without
key = { it.id },LazyColumnkeys rows by list position (0, 1, 2). Prepending shifts every index and leaves localrememberstate on the wrong message.
Show checked explanation
Reading listState.firstVisibleItemIndex > 0 directly subscribes FeedScreen to every index tick (15 scroll recompositions). Wrap it in remember { derivedStateOf { listState.firstVisibleItemIndex > 0 } } so FeedScreen recomposes only when the boolean flips (1 scroll recomposition). Add key = { it.id } to items(...) so prepending keeps remember state tied to each message and lets Compose skip unchanged rows.
Snapshot recomposition counts, derivedStateOf deduplication, positional vs keyed LazyColumn slot mapping, and stability skipping were simulated on CPython 3.12.10 (no Android SDK or Compose compiler installed locally); Compose APIs checked against official Android documentation. Checked by an editor other than the author.
Walkthrough
Jetpack Compose tracks every Snapshot state read during composition and invalidates the enclosing restartable scope whenever that state changes. Reading listState.firstVisibleItemIndex inside FeedScreen invalidates FeedScreen on every index step from 1 through 15, even though showTop changed only once at index 1.
| setup | scroll across 15 items | prepend 1 item (10 visible) | row expanded state |
|---|---|---|---|
direct read, no key | 15 screen recompositions | 10 rows recompose | shifts to wrong message |
derivedStateOf + key | 1 screen recomposition | 1 new row composes (9 skipped) | stays on same message |
Wrapping the condition in remember { derivedStateOf { ... } } confines the rapid firstVisibleItemIndex reads inside the derived calculation. FeedScreen only observes the resulting Boolean, cutting scroll recompositions from 15 down to 1 (2 total compositions including initial render, saving 14 wasted passes).
@Composable
fun FeedScreen(messages: List<Msg>, onSelect: (Long) -> Unit) {
val listState = rememberLazyListState()
val showTop by remember {
derivedStateOf { listState.firstVisibleItemIndex > 0 }
}
Box {
LazyColumn(state = listState) {
items(messages, key = { it.id }) { msg ->
MsgRow(msg, onSelect)
}
}
if (showTop) TopButton()
}
}Why key = { it.id } protects state and enables skipping: Without an explicit key, LazyColumn ties each slot to its index (0, 1, 2). Prepending msg_new puts msg_new in slot 0 and pushes msg_1 to slot 1. Any remember { mutableStateOf(false) } inside slot 0 stays in slot 0, so msg_new inherits msg_1's expanded state while all 10 visible slots receive different inputs and recompose.
With key = { it.id }, Compose moves each slot by ID and skips unchanged MsgRow calls when parameters are stable and equal. Keep Msg fields val (immutable) and avoid mutable var properties so Compose can prove stability. Under modern Compose compilers with strong skipping enabled, Compose also skips composables with unchanged object references, while clean immutable models keep equality skipping predictable.
Common mistakes
- Reading
listState.firstVisibleItemIndexorfirstVisibleItemScrollOffsetdirectly in composition instead of wrapping threshold checks inremember { derivedStateOf { ... } }. - Using
derivedStateOfwithoutremember, which recreates a brand-newStateobject on every recomposition and loses its caching benefit. - Omitting
key = { it.id }inLazyColumnitems(...)for dynamic feeds. Prepending or deleting shifts positional slots, scrambles row state, and disables skipping. - Putting mutable
varproperties inside UI models passed to rows. Mutating avarin place bypasses Snapshot tracking and breaks skippability.
Follow-up questions
- "When is derivedStateOf the wrong tool?" Do not wrap a calculation whose output changes as often as its input, such as
firstName + lastName.derivedStateOfonly saves work when inputs change more frequently than the derived result, like scroll offsets mapped to a boolean threshold. - "How do you avoid recomposing a header when animating its translationY from scroll offset?" Defer the state read to the layout or draw phase with a lambda modifier like
Modifier.graphicsLayer { translationY = offsetProvider() }orModifier.offset { IntOffset(0, y) }. Reading state inside those lambdas skips composition altogether. - "Why does standard Kotlin
List<Msg>historically mark a composable as unstable without strong skipping?" Kotlin'sListinterface is read-only, not deeply immutable, because aMutableListcan back it. Without strong skipping mode, Compose treatsListas unstable unless you wrap it in an@Immutableholder or usekotlinx.collections.immutable.
What a strong answer covers
Explains why direct firstVisibleItemIndex reads trigger 15 recompositions versus 1 with remember { derivedStateOf { ... } }, adds key = { it.id } to preserve slot identity on prepend, and connects immutable models to Compose skipping.
Open in interactive practice deck →