Snapshot state system
Why it matters
- Every
mutableStateOf,mutableStateListOfandderivedStateOfin a Compose app sits on the snapshot system. Knowing how reads and writes are tracked explains stale UI, missed updates and extra recompositions. - Senior Android interviews ask when
derivedStateOfhelps, howsnapshotFlowturns Compose state into a KotlinFlow, and why mutating a list insidemutableStateOfdoes nothing. - Snapshot state is thread-safe and can be written from any thread, but only writes to state objects are tracked. Mutating a plain object held inside state is invisible.
- The same machinery lets Compose run composition in an isolated snapshot and apply all its writes at once, which is why the UI never sees half-applied changes.
The simple explanation
- Think of the app's state as a shared document with version history.
- A snapshot is a private copy of the document at one moment. You can read it while others keep editing.
- A mutable snapshot is a draft: your edits stay private until you apply them, then everyone sees them at once.
- An apply observer is a subscriber who gets told "these cells changed" every time a draft is applied.
derivedStateOfis a formula cell that only tells its readers something changed when its result changes.
What is the snapshot system in Jetpack Compose? It is the state-tracking layer in androidx.compose.runtime that stores every snapshot state object (MutableState, SnapshotStateList, SnapshotStateMap, derived state). It does two jobs: it isolates changes, so code running inside a snapshot sees a consistent view of all state, and it observes reads and writes, so Compose knows which composables to invalidate when state changes.
How a state change reaches the UI.
- While a composable runs, Compose records which state objects it reads (a read observer).
- Your code writes
state.value = x, usually in the global snapshot (the default outside composition). - The global snapshot's changes are applied, and apply observers are told which objects changed. On Android, Compose schedules this for you shortly after a write.
- The Recomposer matches the changed objects against recorded reads and invalidates only those restart scopes. They re-run in the next frame.
| API | Returns | What it does |
|---|---|---|
mutableStateOf(v) | MutableState<T> | Observable value; a write notifies readers if the new value is not equal (default policy) |
mutableStateListOf() | SnapshotStateList<T> | Observable list; add, remove and set notify readers |
derivedStateOf { } | State<T> | Caches a calculation over other state; readers are notified only when the result changes |
snapshotFlow { } | Flow<T> | Re-runs the block when state it read changes; emits only when the result differs from the previous one |
Snapshot.takeSnapshot() | Snapshot | Read-only view frozen at that moment; read it with enter { }, then dispose() |
Snapshot.withMutableSnapshot { } | R | Runs the block in a mutable snapshot and applies its writes atomically at the end |
Snapshot.registerApplyObserver { } | ObserverHandle | Called with the set of changed objects each time a snapshot is applied |
derivedStateOf is for state that changes more often than the value you need. listState.firstVisibleItemIndex changes on every scrolled row, but "show the scroll-to-top button" only flips at index 0. Wrapping that check in remember { derivedStateOf { ... } } means the composable recomposes twice, not on every row. If the result changes as often as the inputs (filtering a list on every keystroke), derivedStateOf only adds overhead; use remember(key) { ... } or the ViewModel.
snapshotFlow turns Compose state into a cold Flow. Collect it in LaunchedEffect to send scroll positions to analytics or save a draft, and it stops when the composable leaves the composition.
Notes
- Only writes to snapshot state objects are tracked.
state.value.add(x)on amutableStateOf(mutableListOf())changes nothing Compose can see; usemutableStateListOf()or assign a new list. mutableStateOfusesstructuralEqualityPolicy()by default: writing a value equal to the current one does not invalidate readers.referentialEqualityPolicy()andneverEqualPolicy()exist for special cases.- Snapshot state can be written from any thread. On Android, Compose sends apply notifications for global snapshot writes for you, so a write from a background coroutine still reaches the UI.
- Thread-safe is not the same as race-free: two coroutines doing
count.value = count.value + 1can lose an update. Do read-modify-write in one place, such as a ViewModel holding aMutableStateFlowwithupdate { }. derivedStateOfmust be wrapped inrememberinside a composable, or a new derived state is created on every recomposition.- Inside
remember { derivedStateOf { ... } }, only snapshot state is tracked. A plain parameter captured in the block is frozen at the first value; add it as arememberkey. snapshotFlowemits only distinct results (likedistinctUntilChanged), and it may skip intermediate values if several writes happen before it runs again.Snapshot.takeSnapshot()gives a read-only snapshot; alwaysdispose()it. Writes need a mutable snapshot (takeMutableSnapshot()withapply(), orwithMutableSnapshot { }).- Composition runs inside a mutable snapshot. Writing state during composition (not in a callback or effect) is a "backwards write" and can cause recomposition loops.
- You rarely call
registerApplyObserverin app code; it is how the runtime (and tools likesnapshotFlow) learn about changes.
Code example
A list screen shows a "scroll to top" button only after the first row scrolls away, and reports the first visible row to analytics while the user scrolls.
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.launch
@OptIn(FlowPreview::class) // debounce is a FlowPreview API
@Composable
fun ArticleList(
titles: List<String>,
onFirstVisibleItem: (Int) -> Unit,
) {
val listState = rememberLazyListState()
val scope = rememberCoroutineScope()
// Changes on every row; the Boolean flips only twice
val showScrollToTop by remember {
derivedStateOf { listState.firstVisibleItemIndex > 0 }
}
// Keep the latest callback without restarting the effect
val currentOnFirstVisible by rememberUpdatedState(onFirstVisibleItem)
LaunchedEffect(listState) {
snapshotFlow { listState.firstVisibleItemIndex }
.debounce(500)
.collect { index -> currentOnFirstVisible(index) }
}
Box {
LazyColumn(state = listState) {
items(titles) { title -> Text(title, Modifier.padding(16.dp)) }
}
if (showScrollToTop) {
FloatingActionButton(
onClick = { scope.launch { listState.animateScrollToItem(0) } },
modifier = Modifier.align(Alignment.BottomEnd).padding(16.dp),
) { Text("Top") }
}
}
}derivedStateOfreadsfirstVisibleItemIndexmany times while scrolling, butArticleListrecomposes only whenshowScrollToTopchanges fromfalsetotrueor back.snapshotFlowre-runs its block whenfirstVisibleItemIndexchanges and emits only new values.debounce(aFlowPreviewAPI in kotlinx.coroutines) sends the position once scrolling pauses.LaunchedEffect(listState)cancels the collection whenArticleListleaves the composition.rememberUpdatedStatemakes the effect call the newestonFirstVisibleItemwithout restarting.
Run the idea in plain Kotlin
A tiny model of derivedStateOf: the derived value is recalculated whenever its input changes, but its reader is only notified when the result changes.
class State<T>(initial: T) {
private val observers = mutableListOf<() -> Unit>()
var value: T = initial
set(v) {
if (v != field) { // structural equality policy
field = v
observers.forEach { it() }
}
}
fun observe(o: () -> Unit) { observers += o }
}
class Derived<T>(private val compute: () -> T, input: State<*>) {
var computeCount = 0
private set
private val readers = mutableListOf<(T) -> Unit>()
var value: T = compute().also { computeCount++ }
private set
init {
input.observe {
val next = compute()
computeCount++
if (next != value) {
value = next
readers.forEach { it(next) }
}
}
}
fun observe(r: (T) -> Unit) { readers += r }
}
fun main() {
val firstVisibleIndex = State(0)
val showScrollToTop = Derived({ firstVisibleIndex.value > 0 }, firstVisibleIndex)
var recompositions = 0
showScrollToTop.observe { show ->
recompositions++
println("Recompose: showScrollToTop = " + show)
}
for (index in listOf(1, 2, 3, 4, 5, 0)) firstVisibleIndex.value = index
println("Index changed 6 times")
println("Derived value computed " + showScrollToTop.computeCount + " times")
println("Reader recomposed " + recompositions + " times")
}Expected output:
Recompose: showScrollToTop = true
Recompose: showScrollToTop = false
Index changed 6 times
Derived value computed 7 times
Reader recomposed 2 times
In production
- A screen received
query: Stringfrom its ViewModel as a parameter and computedval results by remember { derivedStateOf { items.filter { it.contains(query) } } }, whereitemswas aSnapshotStateList. - Results updated when items were added, but typing a new query did nothing.
queryis a plainStringparameter, not snapshot state. Therememberblock captured the first value and never re-ran, andderivedStateOfonly tracks state reads.
- The quick fix made
querya key:remember(query) { derivedStateOf { items.filter { it.contains(query) } } }. A new query now creates a new derived state, and item changes are still tracked inside it. - Later the filtering moved into the ViewModel, combining the item and query flows and running the filter with an injected
Dispatchers.Default. - They added a review rule: inside
remember { derivedStateOf { } }, every non-state value read in the block must be arememberkey. - A Compose UI test types two different queries and asserts the visible rows change both times.
- A list sent an analytics event from a
LaunchedEffectthat collectedsnapshotFlow { listState.firstVisibleItemIndex }. - Every row scrolled past produced an event, so a fast fling sent dozens of events per second.
- The flow was behaving correctly: it emits each distinct index it sees.
- They added
.debounce(500)so only the position after scrolling settles is sent. - For "user reached the end" they switched to
derivedStateOf { lastVisibleIndex >= itemCount - 1 }insidesnapshotFlow, so the flow emits only when that Boolean flips. - They checked event counts in a debug build with a logging analytics client before shipping.
Common mistakes
- Mutating an object held inside
mutableStateOf.state.value.add(x)or changing avarfield of the held object writes nothing to the state, so no reader is invalidated. Use snapshot collections or assign a new immutable value. derivedStateOfwithoutremember. A new derived state is created on every recomposition, so the cache is lost and nothing is saved.- Using
derivedStateOfwhen the result changes as often as the input. Filtering a list by a query that changes per keystroke gains nothing from it. Useremember(key)or do the work in the ViewModel. - Capturing non-state values in
remember { derivedStateOf { } }. Parameters and plain locals are frozen at the first composition. Pass them asrememberkeys. - Writing state during composition. Setting state in the composable body (not in a callback or effect) can trigger another recomposition immediately and loop. Initialise state in
remember { mutableStateOf(initial) }or in the ViewModel. - Collecting
snapshotFlowin a scope that outlives the screen. Collecting it inGlobalScopeor an app-wide scope keeps the screen's state objects alive after the user leaves. Collect inLaunchedEffect. - Assuming thread safety means no races. Concurrent read-modify-write of a
MutableStatefrom several coroutines can lose updates. Keep updates in one owner, such as a ViewModel withMutableStateFlow.update { }.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What is the difference between mutableStateOf and derivedStateOf, and when is derivedStateOf worth using?”
“How does snapshotFlow work and when would you use it?”
“What is a snapshot in Compose?”
“Can you write Compose state from a background thread?”
Quiz
When does derivedStateOf reduce recompositions?
What does snapshotFlow { listState.firstVisibleItemIndex } emit?
val items = remember { mutableStateOf(mutableListOf<String>()) }, then items.value.add("x"). What happens?
What does Snapshot.takeSnapshot() give you?
0 of 4 answered
Mini task
Add derived state and a snapshotFlow side effect (20 min)
- Pick a list screen. Use a
LazyColumnwith at least 50 rows and hoist its state withrememberLazyListState(). - Add a scroll-to-top button. Create
val showButton by remember { derivedStateOf { listState.firstVisibleItemIndex > 0 } }and show a button only when it istrue. The button callsanimateScrollToItem(0)from arememberCoroutineScope(). - Count recompositions. Open Layout Inspector with recomposition counts on. Scroll slowly through 20 rows and note the screen's count.
- Compare. Temporarily replace the derived state with
val showButton = listState.firstVisibleItemIndex > 0and scroll the same distance. The count should rise far more. - Report the position. Add a
LaunchedEffect(listState)that collectssnapshotFlow { listState.firstVisibleItemIndex }.debounce(500)and logs the index withLog.d. - Restore the
derivedStateOfversion.
Done condition: with derivedStateOf, the screen recomposes only when the button appears or disappears, and Logcat shows one index after each scroll pause rather than one per row.