Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 104 ยท State in Compose

State and remember

Learn what state is in Compose, how mutableStateOf triggers recomposition, why remember is needed, how by delegates work, and why plain variables fail.

A screen that never changes is a poster. Real apps react: a counter goes up, a text field fills in, a list loads. In Compose, anything that can change over time and affects what is shown is called state. The rule that drives the whole framework is simple: when state changes, Compose runs the composables that read it again, and the screen updates to match. You never find a view and change it; you change the state and the UI follows.

This lesson introduces mutableStateOf, remember, the by delegate syntax and the idea of snapshot state, and explains why a plain var does not work. The real code needs Android and Compose, so the Compose snippets are read-only. The runnable TryIt blocks are Kotlin stand-ins: one tracks which "scopes" read a value and re-runs only those when it is written, and one models a slot table that makes remember work. They show the mechanism in a few lines; the real runtime is far more elaborate. Thinking in Compose gives the background and Composable Functions explains why composables can run many times.

Why a plain variable fails

Imagine a counter written the way you would in ordinary Kotlin:

Kotlin
// read-only example: needs Android and Compose (this code is BROKEN on purpose)
@Composable
fun BrokenCounter() {
    var count = 0
    Button(onClick = { count++ }) {
        Text("Clicked $count times")
    }
}

It compiles and runs, and does nothing visible. There are two separate problems:

  1. Nobody is told about the change. count++ modifies a local variable. Compose has no idea it changed, so it never schedules a new composition, and the text stays at 0.
  2. Even if the function ran again, count would reset. Each call to BrokenCounter executes var count = 0 from the beginning, because a composable is just a function and local variables vanish when it returns.

So we need two things: a value that notifies Compose when it changes, and a place to keep it across calls. These are mutableStateOf and remember.

mutableStateOf: observable state

mutableStateOf(initial) creates a MutableState<T>: a box holding a value that Compose can observe. Reading .value inside a composable subscribes that part of the UI to the box, and writing .value marks all subscribers as needing to run again.

Kotlin
// read-only example: needs Android and Compose
val count = mutableStateOf(0)
Text("Clicked ${count.value} times")   // this read subscribes the composable
count.value = 1                         // this write schedules recomposition

Compose does not re-run the whole screen. It remembers which composable scope read which state and, on a change, re-executes only those scopes. Writing the same value again (compared with equals by default) is ignored, so assigning count.value = 0 when it is already 0 triggers nothing.

remember: keep a value across recompositions

remember { ... } runs its lambda the first time a composable is called, stores the result in the composition, and returns the stored object on every later recomposition:

Kotlin
// read-only example: needs Android and Compose
@Composable
fun Counter() {
    val count = remember { mutableStateOf(0) }
    Button(onClick = { count.value++ }) {
        Text("Clicked ${count.value} times")
    }
}

Now both problems are solved: the MutableState object survives because remember keeps it, and writes to it notify Compose. Two details to know:

  • remember stores a value per place in the composition. Two Counter() calls on the same screen each get their own state, because each call site and each instance has its own slot.
  • When the composable leaves the composition (for example it is hidden by an if), the remembered value is forgotten. Coming back creates a fresh one. remember does not survive screen rotation or process death either; for that there is rememberSaveable, covered in rememberSaveable, derivedStateOf and Collections and Configuration Changes and Saved State.

remember can take keys: remember(userId) { loadProfile(userId) } recomputes when userId changes and otherwise returns the stored value. Use keys for derived values that depend on inputs, and not for state that should persist while the inputs change.

The by delegate

Writing .value everywhere is noisy. MutableState provides getValue and setValue operator functions, so you can use a Kotlin property delegate (Delegated properties explains how they work):

Kotlin
// read-only example: needs Android and Compose
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue

@Composable
fun Counter() {
    var count by remember { mutableIntStateOf(0) }
    Button(onClick = { count++ }) {
        Text("Clicked $count times")
    }
}

count now looks like a plain Int, but every read and write goes through the MutableState. The two imports (getValue, setValue) are required for by to compile, and forgetting them is the most common beginner error. mutableIntStateOf, mutableLongStateOf, mutableFloatStateOf and mutableDoubleStateOf are primitive-specialized versions that avoid boxing; use them for numbers and mutableStateOf for everything else.

A convention worth following: a State that is read in the composable usually comes with a val, as in val count = remember { mutableIntStateOf(0) }, if you pass the state object itself to other code; use var ... by when you only want the value.

Observable state in a few lines (stand-in)

Here is the mechanism without the Android parts. A State keeps a set of scopes that read it. A Recomposer tracks which scope is running, so a read inside a scope registers that scope as a subscriber. A write marks the subscribers dirty, and flush re-runs them, once each. Notice that only the scope that read the changed state runs again, and that writing an equal value does nothing.

Kotlin Writes trigger only the scopes that read the state (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 last case shows that several writes before the next frame cause one recomposition with the latest value. The real runtime does this work with a snapshot system, described next.

Snapshot state

Compose state lives in a snapshot system, similar to the version-control idea of a consistent view of data. Every read of a state object during composition is recorded, and writes made on other threads or inside Snapshot.withMutableSnapshot { } are applied atomically, so a composition never sees half of a multi-field update. You rarely touch the API directly, but it explains two facts:

  • Compose only notices a change when a state object is written. If you hold a plain MutableList inside mutableStateOf and call list.add(x), nothing is written to the state box, and the UI does not update. Replace the value (state.value = list + x) or use mutableStateListOf, which is observable (next lessons).
  • State is meant to be written from the main thread or in controlled snapshots. A ViewModel will expose state through flows rather than raw compose state across threads (StateFlow and collectAsStateWithLifecycle).
flowchart LR
    E["Event<br/>(tap, data arrives)"] --> W["Write state value"]
    W --> I["Invalidate scopes<br/>that read it"]
    I --> R["Recompose those scopes"]
    R --> U["UI shows new state"]
    U -.->|"user acts again"| E

State drives the UI: events write state, only readers of that state are recomposed.

How remember keeps a value (stand-in)

Where does remember keep the value? In a structure called the slot table. Each composable call occupies positions in order; on recomposition the same calls happen in the same order, so a call finds "its" slot by position. The stand-in below models just that: a list of slots, an index reset at the start of each composition, and a remember that returns the stored value, or recomputes it when its key changed. A plain local variable inside Counter is reset on every call, as in the broken example above.

Kotlin A slot table behind remember (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 plain variable restarts from zero each time, while the remembered box accumulates. The search result is calculated only twice for three calls, because the second call used the same key.

Rules of thumb

  • Hold UI state in remember { mutableStateOf(...) } (or rememberSaveable when it must survive rotation).
  • Prefer var x by remember { ... } and remember the getValue/setValue imports.
  • Do not mutate objects hidden inside a state; assign a new value or use observable collections.
  • Do not use remember as a cache for work that depends on changing inputs unless you pass those inputs as keys.
  • Keep state as low in the tree as possible and as high as necessary. Sharing it between composables is the topic of the next chapter lessons (State Hoisting and Unidirectional Data Flow).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does var count = 0 followed by count++ in a click handler not update a composable's text?

    A plain variable is invisible to Compose, so no recomposition is scheduled, and local variables are recreated on every call anyway.
  2. 2. What does remember { mutableStateOf(0) } do?

    remember runs the lambda the first time, stores the result in the composition, and returns the stored object afterwards. It does not survive process death; rememberSaveable can.
  3. 3. What is needed for var count by remember { mutableIntStateOf(0) } to compile?

    The by syntax calls the getValue and setValue operator extension functions of MutableState, which must be imported.
  4. 4. A mutableStateOf holds a MutableList and you call list.add(item). What happens to the UI?

    Compose observes writes to the state's value. Mutating an object inside it is invisible. Assign a new list or use mutableStateListOf.
  5. 5. What happens when you write an equal value to a MutableState (count = 0 when it is already 0)?

    The default policy compares the new value with the old one using equals; an equal value does not invalidate readers.

Summary

  • State is data that changes over time and affects the UI; when it changes, Compose recomposes the composables that read it.
  • A plain var fails twice: Compose is not notified, and locals reset whenever the function runs again.
  • mutableStateOf creates observable state; reading .value subscribes the reader, writing a different value invalidates it.
  • remember keeps a value in the composition across recompositions, per call site; it is forgotten when the composable leaves, so use rememberSaveable for rotation.
  • var x by remember { mutableIntStateOf(0) } needs the getValue/setValue imports.
  • Mutating an object inside a state is invisible; replace the value or use observable collections.
  • The Compose code is read-only; the TryIt blocks are stand-ins for subscription and the slot table.

Next: State Hoisting and Unidirectional Data Flow