Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 104 ยท State in Compose

rememberSaveable, derivedStateOf and Collections

Keep Compose state across rotation with rememberSaveable and custom Savers, avoid needless work with derivedStateOf, and use state-aware collections and snapshotFlow.

remember keeps a value across recompositions, but it lives only as long as the composition does. Rotate the phone and Android recreates the activity, so everything you stored with plain remember is gone. A scroll-driven button flickers on every frame because you computed a boolean in the wrong place. A mutableStateOf(listOf(...)) that you "update" by mutating the list never refreshes the screen. These three problems have three tools: rememberSaveable, derivedStateOf and the state-aware collections.

The real Compose code in this lesson is read-only because it needs the Android SDK. The runnable TryIt blocks are Kotlin stand-ins: one models how derived values are cached, the other models how a saver turns an object into a bundle and back. They are simplified models of the ideas, not the Compose runtime.

rememberSaveable: surviving recreation

rememberSaveable works like remember, but it also writes the value into the activity's saved-instance-state Bundle, the same mechanism you will meet in Configuration Changes and Saved State. When the activity is recreated, because of a rotation, a dark-mode switch, a language change or even process death while the app was in the background, the value is read back from the bundle.

Kotlin
// read-only example: needs Compose
@Composable
fun SearchBox() {
    var query by rememberSaveable { mutableStateOf("") }
    OutlinedTextField(value = query, onValueChange = { query = it })
}

Types that fit in a Bundle work automatically: primitives, String, arrays, and anything Parcelable or Serializable. For a Parcelable you add the @Parcelize annotation from the Kotlin Parcelize plugin:

Kotlin
// read-only example: needs Compose and the kotlin-parcelize plugin
@Parcelize
data class Filter(val tag: String, val onlyUnread: Boolean) : Parcelable

@Composable
fun Inbox() {
    var filter by rememberSaveable { mutableStateOf(Filter("all", false)) }
    // ...
}

Rules of thumb for what to save:

  • Save small, user-driven UI state: text being typed, a selected tab, an expanded section, a scroll position. Do not save large lists or images: the bundle is limited (the whole saved state shares a transaction budget of roughly one megabyte) and exceeding it crashes with TransactionTooLargeException.
  • Do not save what you can reload: data from a database or the network belongs in a ViewModel or repository and is fetched again.
  • Do not save things that cannot be written to a bundle, such as Context, lambdas, or open streams.
  • remember is still right for derived or recreatable objects, such as a FocusRequester or a computed value.

rememberSaveable also accepts inputs, like remember(key): when a key changes, the stored value is dropped and recomputed.

Custom Savers

If a type is not Bundle-friendly, you give rememberSaveable a Saver. A Saver<Original, Saveable> has two functions: save turns the object into something that fits in a bundle, and restore turns it back (returning null means "cannot restore").

Kotlin
// read-only example: needs Compose
class City(val name: String, val population: Int)

val CitySaver = Saver<City, Map<String, Any>>(
    save = { mapOf("name" to it.name, "population" to it.population) },
    restore = { City(it["name"] as String, it["population"] as Int) }
)

@Composable
fun CityPicker() {
    var city by rememberSaveable(stateSaver = CitySaver) {
        mutableStateOf(City("Oslo", 709_000))
    }
}

Two helpers write the boilerplate for you: listSaver(save = { listOf(it.name, it.population) }, restore = { City(it[0] as String, it[1] as Int) }) and mapSaver(...), which uses keys instead of positions. Note the stateSaver parameter name: when the saved value is wrapped in mutableStateOf, the saver describes the inner type.

The stand-in below models the full round trip. Bundle is a plain MutableMap, Saver is an interface with the two functions, and Registry plays the part of a composition that stores values under keys. The "rotation" saves everything, throws the registry away and builds a new one that restores from the bundle. The plain value, stored without a saver, is lost, just like a remember value.

Kotlin A saver and a rotation (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Look at the output: the city comes back from the bundle (the default is not used), while the plain remember value starts fresh.

derivedStateOf: compute from state, notify less

Sometimes a value depends on fast-changing state but changes slowly itself. The classic example is a "scroll to top" button that appears once the list has scrolled past the first item. listState.firstVisibleItemIndex changes many times while the user scrolls, but index > 0 flips only once.

Kotlin
// read-only example: needs Compose
@Composable
fun MessageList(messages: List<String>) {
    val listState = rememberLazyListState()
    val showScrollToTop by remember {
        derivedStateOf { listState.firstVisibleItemIndex > 0 }
    }

    Box {
        LazyColumn(state = listState) { items(messages) { Text(it) } }
        if (showScrollToTop) {
            ScrollToTopButton()
        }
    }
}

If the boolean were computed directly in the composable body (val show = listState.firstVisibleItemIndex > 0), the body would read the index and so recompose on every index change, even when show stays true. derivedStateOf moves that read into a derived state object. The composable reads only the derived value, so it recomposes only when the boolean actually changes. Derived state is also cached: it recomputes only when one of the states it read changes.

Use it when the inputs change more often than the result. Do not use it when the result changes as often as the input (derivedStateOf { name.uppercase() } just adds overhead; compute it directly, or with remember(name) if it is expensive). Always wrap it in remember so the derived object survives recomposition, and pass keys to remember if it uses plain parameters:

Kotlin
// read-only example: needs Compose
@Composable
fun Highlight(items: List<String>, threshold: Int) {
    val big by remember(items, threshold) {
        derivedStateOf { items.count { it.length > threshold } }
    }
    Text("$big long items")
}

The stand-in below counts how often a derived value is recomputed and how often the "screen" would update. Observable is a value with a version number. Derived caches its result and only recomputes when the version of its input has changed. The screen is notified only when the cached result differs from the one it saw before.

Kotlin Derived value caching (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The index was written ten times, but the screen only had to change three times: the first draw, when the button appeared and when it disappeared. (The calculation itself reran on every write, since each write is a new version. It is cheap; the saving is in the recompositions.)

State-aware collections

mutableStateOf(mutableListOf(1, 2)) is a common trap. Compose only notices when the reference in the state is replaced, not when you add an item to the list inside it, so list.value.add(3) changes nothing on screen.

Use the observable collections instead:

Kotlin
// read-only example: needs Compose
val todos = remember { mutableStateListOf("Buy milk", "Walk dog") }
val selected = remember { mutableStateMapOf<Int, Boolean>() }

Button(onClick = { todos.add("Read a book") }) { Text("Add") }

mutableStateListOf and mutableStateMapOf record reads and writes per element, so adding, removing or replacing an item invalidates exactly the scopes that read the list. Two cautions:

  • They are not saved by rememberSaveable automatically. Wrap them in a saver such as listSaver, or keep the list in a ViewModel.
  • For data that comes from a repository, prefer an immutable List inside a StateFlow or a single state object and replace it, so changes are atomic. UI State, Events and MVI-style Modelling shows that style.

The other direction, getting a stream of values out of state, is snapshotFlow. It turns the state reads inside its block into a Flow that emits whenever the result changes (and never emits duplicates):

Kotlin
// read-only example: needs Compose and coroutines
LaunchedEffect(listState) {
    snapshotFlow { listState.firstVisibleItemIndex }
        .distinctUntilChanged()
        .collect { index -> analytics.logScrollPosition(index) }
}

This is the right tool for sending scroll or text changes to non-Compose code, such as analytics or a search request. Side Effects explains LaunchedEffect, and Flows covers collect and operators.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens to a value stored with plain remember when the user rotates the phone?

    remember only lasts as long as the composition. A rotation recreates the activity, so use rememberSaveable (or a ViewModel) for state that must survive.
  2. 2. When is derivedStateOf the right tool?

    derivedStateOf makes the composable read the derived value, so it recomposes only when the result changes, for example a boolean that flips once while a scroll index changes constantly.
  3. 3. Why does mutableStateOf(mutableListOf(1, 2)) followed by list.value.add(3) not update the UI?

    The state holds a reference to the same list object, and add mutates it without writing to the state. Use mutableStateListOf or replace the list with a new one.
  4. 4. What does the restore function of a Saver return when it cannot rebuild the object?

    Returning null from restore tells rememberSaveable there is nothing usable, so it falls back to the initial value computed by its lambda.

Summary

  • Use rememberSaveable for small, user-driven UI state that must survive recreation; it stores values in the saved-state bundle.
  • Bundle-friendly types work automatically; use @Parcelize, or give a Saver (listSaver, mapSaver, or your own) for other types.
  • Do not save large data, reloadable data or unsaveable objects.
  • derivedStateOf fits when inputs change more often than the result; wrap it in remember and do not use it for one-to-one transforms.
  • mutableStateListOf and mutableStateMapOf observe element changes; plain mutable collections inside state do not.
  • snapshotFlow turns state reads into a Flow for non-UI work such as analytics.
  • The Compose code is read-only; the TryIt blocks model savers and derived caching.

Next: Side Effects: LaunchedEffect, DisposableEffect and Friends