Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 104 ยท State in Compose

Recomposition and Stability

Understand what triggers recomposition in Jetpack Compose, how skipping works, what stable types are, what strong skipping mode changes and how keys help.

Compose does not redraw the whole screen when something changes. It re-runs only the composable functions that might produce a different result, and it skips the rest. That process is called recomposition, and it is the reason a Compose app can stay fast even when the UI tree is large. It is also the reason that writing a composable carelessly can make it run far more often than you expected.

This lesson explains what triggers recomposition, how Compose decides to skip a function, what stable means, what changed with strong skipping mode, and how to avoid the usual mistakes. The real code needs the Android SDK, so the Compose snippets are read-only. The TryIt blocks are Kotlin stand-ins that model the decision rule ("same inputs, skip") so you can count what runs. They are not the Compose compiler. If state itself is new to you, read State and remember first.

What triggers recomposition

A composable function is re-run when something it read during its last run changes. Compose tracks reads of snapshot state (values created with mutableStateOf, mutableStateListOf, derivedStateOf and so on). When one of those values is written with a new value, every composition scope that read it is marked invalid and is scheduled to run again on the next frame.

Kotlin
// read-only example: needs Compose
@Composable
fun Greeting(name: String) {
    Text("Hello, $name")
}

@Composable
fun Screen() {
    var name by remember { mutableStateOf("Ada") }
    Column {
        Greeting(name)
        Button(onClick = { name = "Grace" }) { Text("Rename") }
    }
}

Reading name happens inside Screen, when it passes the value to Greeting. After the click, Screen's scope is invalid and runs again, calls Greeting("Grace"), and Greeting runs because its input differs. The Button call has the same inputs as before (a new lambda is created but, as you will see, it is remembered), so it can be skipped.

Three facts help you reason about it:

  • Recomposition is triggered by state reads, not by function calls. Writing a value that nothing read causes no work.
  • The scope is the smallest enclosing restartable function or lambda, not always the whole composable. A state read inside a Text lambda only reruns that lambda.
  • Recomposition can happen often and in any order. A composable can be recomposed on every animation frame, skipped, or even abandoned and restarted. So composables must be fast and free of side effects (see Side Effects).
flowchart LR
    W["State written"] --> I["Scopes that read it<br/>are invalidated"]
    I --> R["Next frame: re-run<br/>those scopes"]
    R --> C{"Inputs equal<br/>to last time?"}
    C -->|"yes"| S["Skip the call"]
    C -->|"no"| X["Run the function body"]

A state write invalidates the scopes that read it; each call is then skipped if its inputs are unchanged.

Skipping: same inputs, same output

Compose assumes that a composable is a function of its parameters: if the arguments are equal to the previous call, the output would be the same, so the call can be skipped. A function that can be skipped is called skippable. The compiler adds code at the start of each composable that compares the new parameters with the ones stored from the last run.

Here is a stand-in for that check. Skippable1 stores the last argument; when a new call arrives with an equal argument, it does not run the body. The counter shows how many times each "composable" actually ran.

Kotlin Counting recompositions by input equality (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.

Title ran once even though its parent ran three times: that is skipping. The real mechanism works per parameter and also considers whether a parameter was changed or "static", but the principle is the same.

Stable and unstable types

Comparing parameters only works if the comparison is trustworthy. Compose therefore classifies types as stable or unstable. A type is stable if:

  • equals always gives the same answer for the same two instances (equal stays equal),
  • when a public property changes, Compose is notified (for example the property is a MutableState), and
  • all public properties are themselves stable.

Primitives, String, function types and enums are stable. A data class whose properties are all val and all stable is inferred to be stable. A class with a var property that is a plain field is unstable, because it can change without Compose being told. The collection interfaces List, Set and Map are treated as unstable, because the instance behind a List may well be an ArrayList that gets mutated. Classes from modules that were compiled without the Compose compiler are also treated as unstable.

Kotlin
// read-only example: needs Compose
data class Product(val id: Long, val title: String)          // stable (val + stable types)
data class Cart(val items: List<Product>)                    // unstable: List
class Counter { var value = 0 }                              // unstable: plain var

@Immutable
data class Receipt(val lines: List<String>)                  // promise: never changes
@Stable
class Selection { var id by mutableLongStateOf(-1) }         // promise: changes are observable

@Immutable and @Stable are promises you make to the compiler. It does not verify them. If you annotate a class and then mutate it behind Compose's back, the UI will show stale values. Alternatives that avoid the problem are the kotlinx.collections.immutable types (ImmutableList, PersistentList), which the compiler knows are stable when you add its library, or wrapping the list in a small class annotated @Immutable. You can also add a stability configuration file that lists your own classes as stable.

Strong skipping mode

Historically, a composable with any unstable parameter was not skippable at all, so it re-ran every time its parent did. A single List<Product> parameter was enough to make a whole list item re-run on every frame.

Strong skipping mode changes the rule. It is enabled by default in the Compose compiler since Kotlin 2.0.20, and with it:

  • Composables with unstable parameters can be skipped.
  • Stable parameters are compared with equals() as before.
  • Unstable parameters are compared by instance identity: skipped only if it is the same object (===) as last time.
  • Lambdas that capture values are automatically remembered, keyed on the captured values, so an inline onClick = { vm.save(id) } no longer changes on every recomposition.

Identity comparison means that a new List with equal contents is a different instance, so the function still runs. The stand-in below models all three policies so you can compare them. stable = true models a stable type, compared by equality; otherwise the policy decides whether unstable arguments are compared by identity or never skipped.

Kotlin Stable vs unstable parameters (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 row is the lesson: even with strong skipping, a freshly copied list defeats skipping. Create the list once (in a ViewModel or inside remember) and pass the same instance.

Keys and lists

Compose identifies the calls in a composition by their position in the source and the order of the calls. In a loop this is not enough: if the list is reordered, items are matched by position, so item state lands on the wrong item. The fix is to give each element a stable identity with a key.

Kotlin
// read-only example: needs Compose
Column {
    for (task in tasks) {
        key(task.id) {
            TaskRow(task)
        }
    }
}

LazyColumn {
    items(tasks, key = { it.id }) { task -> TaskRow(task) }
}

With keys, inserting or moving a task keeps each row's remembered state with the right task, and rows whose input did not change are skipped. Lazy lists are covered in Lazy Lists and Grids.

Common over-recomposition mistakes

Most performance problems come from a short list of habits:

  • Reading fast-changing state too high. Reading a scroll offset or animation value in a parent composable recomposes the parent and all its children every frame. Read it as low as possible, or defer the read into a lambda such as Modifier.offset { IntOffset(x, 0) } or graphicsLayer { alpha = a }, which runs in the layout or draw phase instead of recomposition.
  • Creating new objects as parameters. Item(tags = listOf("new")) allocates a new list on every call. Hoist it or remember it.
  • Doing expensive work in the body. Sorting or filtering a list inside a composable repeats on every run. Use remember(list) { list.sorted() } or compute it in the ViewModel.
  • Passing a whole object when one field is needed. Avatar(user) re-runs when anything on the user changes; Avatar(url = user.avatarUrl) re-runs only when the URL does.
  • Forgetting that a var in a class is not observable. Mutating a field in a normal class does not trigger recomposition. Use state, or replace the object with a copy (copy(...)).

Do not optimize blindly. Compose is fast by default, and a recomposition that is skipped or cheap is free. Measure first: the Layout Inspector shows recomposition and skip counts per composable, and the Compose compiler can produce a stability report that lists which parameters it considers unstable. Performance and Profiling returns to measuring.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What causes a composable to be re-run?

    Compose records which state objects each scope reads. When one is written, the scopes that read it are invalidated and re-run on the next frame.
  2. 2. Which type is treated as unstable by default?

    List is an interface that might be backed by a mutable collection, so it is treated as unstable. Primitives, String and fully stable data classes are stable.
  3. 3. With strong skipping mode, how is an unstable parameter compared to decide whether to skip?

    Strong skipping compares stable parameters with equals() and unstable ones with ===, so passing the same instance allows a skip but passing an equal copy does not.
  4. 4. Why use key(id) or items(key = ...) for list rows?

    Without keys, rows are matched by position, so inserting or reordering shifts remembered state onto the wrong item. Keys tie state to the data.

Summary

  • Recomposition re-runs only the scopes that read state which changed; everything else is skipped when its inputs are equal.
  • Composables must be cheap and side-effect free, because they can run often and in any order.
  • Primitives, strings, enums, function types and all-val data classes of stable types are stable; List, plain var classes and types from non-Compose modules are unstable.
  • @Immutable and @Stable are unchecked promises; immutable collections or small wrappers are safer.
  • Strong skipping mode (default since Kotlin 2.0.20) lets unstable parameters skip by identity and remembers capturing lambdas.
  • Use keys in lists, read fast-changing state as low as possible, and avoid allocating fresh parameter objects.
  • Measure with the Layout Inspector before optimizing. The code here is read-only; the TryIt blocks model the skipping rule.

Next: rememberSaveable, derivedStateOf and Collections