Lists with LazyColumn
Why it matters
- Almost every app screen is a list: feed, chat, orders, settings. Slow or jumpy lists are the most visible quality problem users notice.
- Most list bugs in Compose come from one missing argument: the key. State lands on the wrong row and scroll position jumps.
- "How is LazyColumn different from RecyclerView?" and "Why do you need keys?" are common interview questions.
- A
Columnwith 500 children composes all 500. ALazyColumndoes not. Knowing the difference prevents jank and crashes.
The simple explanation
Think of a waiter with a tray. The kitchen has 1,000 dishes, but the waiter only carries what fits on the table in front of you. When you scroll, he takes away dishes you passed and brings new ones.
- The dishes are your data. The table is the screen.
- If every dish has a name tag (a key), the waiter knows which dish is which after the menu changes. Your "extra spicy" note stays on the right dish.
- Without name tags he tracks dishes by seat number (position). Remove the first dish and every note slides to the wrong plate.
- If dishes come in types (soup, dessert), he reuses the same kind of bowl. That is content type.
The real names:
| Name | What it does |
|---|---|
LazyColumn / LazyRow | Composes and lays out only visible items (plus a small buffer) |
LazyListScope.items(list, key, contentType) | Adds one item per element of a list |
item { } | Adds one single item, such as a header |
itemsIndexed | Same as items, but gives you the index too |
key | A stable, unique id per item. Must be a type that can go into a Bundle on Android |
contentType | A label for the kind of item, so Compose can reuse composition nodes |
LazyListState | Holds scroll position. Create it with rememberLazyListState() |
contentPadding | Padding inside the scroll area, so items scroll under the bars |
Notes
- A lazy list composes items on demand. It does not recycle Views like
RecyclerView. It disposes items that scroll far away and composes new ones. - Without a key, item identity is its position. Insert or remove above an item and its
rememberstate belongs to a different data item. - With a key, Compose matches items by key. State, animations and scroll position follow the item, not the slot.
- Keys must be unique in the list. A duplicate key crashes with an
IllegalArgumentExceptionthat says the key was already used. - Good keys: database ids, server ids. Bad keys: list index,
hashCode()of a mutable object, random values created during composition. contentTypehelps when the list mixes very different items, such as headers, ads and rows. Compose reuses nodes only between items of the same type.- Use
rememberLazyListState()to read or control scroll. ReadlistState.firstVisibleItemIndexthroughderivedStateOfso the screen does not recompose on every scrolled pixel. - Put
Modifier.animateItem()on an item to animate insert, remove and reorder. It needs keys to work correctly. - Never nest a vertically scrolling lazy list inside a
verticalScrollparent. It crashes because the child gets infinite height. Use one lazy list with several item blocks. - Use
LazyVerticalGridfor grids andLazyRowfor horizontal rails. The same key rules apply.
Code example
A list with a header row and message rows. Rows have a stable id as key, and the header has its own content type.
data class Message(val id: Long, val text: String)
@Composable
fun MessageList(messages: List<Message>, modifier: Modifier = Modifier) {
val listState = rememberLazyListState()
// Recomposes only when the boolean changes, not on every scroll pixel.
val showJumpToTop by remember {
derivedStateOf { listState.firstVisibleItemIndex > 3 }
}
Box(modifier) {
LazyColumn(
state = listState,
contentPadding = PaddingValues(16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
item(key = "header", contentType = "header") {
Text("Messages", style = MaterialTheme.typography.titleLarge)
}
items(
items = messages,
key = { it.id }, // stable and unique
contentType = { "message" },
) { message ->
// State here follows the message, because of the key.
var expanded by rememberSaveable { mutableStateOf(false) }
Card(
onClick = { expanded = !expanded },
modifier = Modifier.fillMaxWidth().animateItem(),
) {
Text(
text = message.text,
maxLines = if (expanded) Int.MAX_VALUE else 2,
modifier = Modifier.padding(12.dp),
)
}
}
}
if (showJumpToTop) { /* show a button that calls listState.animateScrollToItem(0) */ }
}
}Notes on the sample:
rememberSaveableinside an item is keyed by the item key too, so expanded state survives scrolling away and back.animateItem()is called insideLazyItemScope, which is why it is available there.animateScrollToItemis a suspend function, so a click lambda cannot call it directly. Get a scope withrememberCoroutineScope()in the composable, then callscope.launch { listState.animateScrollToItem(0) }from the click.
Run the idea in plain Kotlin
Compose cannot run in the browser, but the identity rule can. Here "checked" state is stored by position and by key. Then the first item is removed.
fun main() {
val items = mutableListOf("A", "B", "C")
val checkedByPosition = mutableSetOf(0) // user checked the first row (A)
val checkedByKey = mutableSetOf("A") // same, but stored by id
items.removeAt(0) // A is deleted
val wrong = items.filterIndexed { index, _ -> index in checkedByPosition }
val right = items.filter { it in checkedByKey }
println("By position, still checked: " + wrong) // [B] wrong item
println("By key, still checked: " + right) // [] correct
}In production
- An orders screen let users tick orders for bulk actions. After a new order arrived at the top, users saw their ticks move to the wrong orders. One user bulk-cancelled the wrong order.
- Developers could not see it with static test data. It only happened when the list changed while a row was selected.
- Cause:
items(orders)had nokey. Each row kept itsrememberstate by position. A new item at index 0 shifted all data down by one, but the state stayed in place.
- Reproduce with a fake repository that inserts an item at the top every few seconds. Tick the second row and watch the tick move.
- Pass
key = { it.orderId }toitems. - Better: do not keep selection in row state at all. Hold
selectedIds: Set<Long>in the ViewModel. Rows are then pure functions of data. - Add a UI test that inserts at index 0 and asserts that the same order is still selected.
- After a pagination change, the feed crashed for some users with a duplicate key error. It never happened in QA.
- Cause: the server returned the same post on page 1 and page 2 when new posts were published between requests. The code appended pages without removing duplicates, and the key was the post id.
- Merge pages by id, for example
(old + new).distinctBy { it.id }, or store posts in a database with the id as primary key and show the query result. - Unit test the merge with overlapping pages.
- Keep the key unique by design. Do not hide the bug by adding the index to the key, because that brings back the shifting problem.
Common mistakes
- Leaving out
keyon a list that changes. It looks fine until items are inserted, removed or sorted. - Using the index as the key. It is the same as having no key. It breaks state on every insert or delete.
- Putting a
LazyColumninsideModifier.verticalScroll. It crashes with infinite height constraints. Use one lazy list, withitem { }blocks for the other content. - Reading
firstVisibleItemIndexdirectly in composition. The whole function recomposes on scroll. Wrap it inderivedStateOf. - Doing heavy work inside the item lambda. Sorting, formatting or parsing runs again as items enter. Prepare the data in the ViewModel.
- Holding row state in
rememberwhen it belongs to the data. Selection, expanded and checked flags should live in the ViewModel, keyed by id.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“Why do you pass a key to items in a LazyColumn?”
“How is LazyColumn different from RecyclerView?”
“Why can you not put a LazyColumn inside a Column with verticalScroll?”
“How do you avoid recomposing the whole screen on every scroll event?”
Quiz
A LazyColumn has no key. A new item is inserted at the top. What can go wrong?
Which is the best key for a list of orders loaded from a database?
What does contentType do?
Why does a LazyColumn inside a verticalScroll Column crash?
0 of 4 answered
Mini task
Build a to-do list screen, then break it on purpose and fix it:
- Show 20 rows in a
LazyColumn. Each row has aCheckboxwhose state is inrememberinside the item. - Add a button that inserts a new row at the top.
- Tick the third row, press the button, and note which row is ticked.
- Add
key = { it.id }and repeat. Note the difference. - Move the checked state into the ViewModel as
Set<Int>of ids.
You are done when the tick stays on the same to-do after any insert or delete, and you can explain why the first version failed.