State lists and mutation

Jetpack Compose Junior Kotlin 2.0+ API 24+ Reviewed By Best Latest Apps

Spot the bug

Tapping Add doesn't show the new row. Which line is the bug?

  1. @Composable
  2. fun Todo() {
  3. val items by remember { mutableStateOf(mutableListOf("Milk")) }
  4. Column {
  5. items.forEach { Text(it) }
  6. Button(onClick = { items.add("Eggs") }) { Text("Add") }
  7. }
  8. }
Hint 1 of 1

Which writes does Compose observe?

Choose an answer, then open Show answer below to check it.

Show answer
  • Answer: line 6 Button(onClick = { items.add("Eggs") }) { Text("Add") }

add mutates the list but doesn't write the State, so Compose isn't told. Use mutableStateListOf("Milk"), or a var holding an immutable List and items = items + "Eggs".

30-second answer

mutableStateOf(mutableListOf()) only notices when you assign a new value. Calling add on the list inside changes the list but not the State, so nothing recomposes. Either replace the list (items = items + new) with an immutable List, or use mutableStateListOf(), whose add and remove are tracked by Compose.

Practise saying it · 30 s. No recording, just a timer

Explain how to keep a list in Compose state.

Say your answer out loud, then check which of these points you covered:

  • Mutating a plain list isn't observed
  • Replace the list or use mutableStateListOf
  • Prefer immutable lists in ViewModels

Deep dive

Compose tracks reads and writes of snapshot state objects; a plain MutableList isn't one.

mutableStateMapOf is the map equivalent.

In ViewModels, prefer immutable lists in a StateFlow; snapshot lists are handy for local UI state.

Snapshot state can be written from any thread; Compose applies the change on the next frame.

Common mistakes

  • Mutating a plain list inside mutableStateOf.
  • Exposing SnapshotStateList from a ViewModel so anyone can mutate it.
  • Using remember { mutableListOf() } and expecting updates.

Senior take & follow-ups

Say 'only writes to state objects are observed', then give both fixes.

Follow-up questions

Think of your answer first, then open the hint.

  1. What's a snapshot?

    Show hint

    Compose's isolated view of state, which makes changes visible atomically.

  2. Is mutableStateListOf safe across threads?

    Show hint

    Writes are snapshot-isolated, but concurrent edits from many threads can still conflict.

Suggest a fix if something here is wrong or out of date.