skip to content

State and Recomposition

remember, mutableStateOf, derivedStateOf and rememberSaveable, what triggers recomposition, and state hoisting. A near-certain question: most Compose bugs are state kept or read in the wrong place.

on this pageshow

explore

questions

6

In Jetpack Compose, why does a quantity counter kept in a plain local `var` never update, and what do `remember` and `mutableStateOf` each fix?

level: juniorimportance: must knowfreq 85%

answer

  1. observed versus kept
  2. a write reschedules whoever read it
  3. recomposition re-runs the function body
  4. stored in the Composition, forgotten on exit
  5. equal writes are not changes

basics

~20 s

A plain local is neither observed nor kept: changing it schedules nothing, and every recomposition re-runs the function and resets it. mutableStateOf makes writes recompose whatever read the value; remember keeps that state object in the Composition between recompositions.

solid answer

~50 s

Compose updates the screen only by re-running composables, and it only re-runs the ones that read **snapshot state** that changed. A plain `var count = 1` is invisible to the runtime, so `count++` in an `onClick` schedules nothing, and if something else recomposes the function, the declaration runs again and resets it. `mutableStateOf(1)` returns an observable `MutableState`: reading `.value` during composition subscribes the current recompose scope, and a later write schedules those readers to recompose. On its own, though, the call runs again on every recomposition and hands back a fresh object holding the initial value. `remember { }` stores the object in the Composition at that call site and returns the same instance until the composable leaves the Composition. So the pair is `var quantity by remember { mutableIntStateOf(1) }`. With the default `structuralEqualityPolicy()`, writing a value `==` to the current one is not a change.

code

kotlin · 18 lines
kotlin
import androidx.compose.foundation.layout.Row
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue

@Composable
fun QuantityStepper() {
    var quantity by remember { mutableIntStateOf(1) }
    Row {
        Button(onClick = { if (quantity > 1) quantity-- }) { Text("-") }
        Text("Qty: $quantity")
        Button(onClick = { quantity++ }) { Text("+") }
    }
}

go deeper

for a junior

Recall the two jobs separately: mutableStateOf makes writes visible to Compose, remember keeps the object across recompositions. Be ready to write the by remember declaration from memory.

for a middle

Explain the mechanism: a read during composition subscribes the recompose scope, an assignment schedules it, and the equality policy filters equal writes. Show why in-place list mutation is not a write.

for a senior

Diagnose from symptoms: a value that snaps back means an unremembered state; a UI that ignores a change means the write never went through state. Name the lint checks that catch both before review does.

for a principal

Treat state declarations as a codebase convention: primitive state factories, immutable collections or snapshot lists, and lint checks raised to errors in CI so the classic bugs cannot merge.

## Why a plain local fails Jetpack Compose builds UI by calling **composable functions**. The first run is the **initial composition**; when data changes, Compose runs the affected functions again, which is **recomposition**. There is no `setText()` to call: the only way to change what is on screen is for a composable to run again and emit something different. A plain Kotlin local such as `var quantity = 1` defeats this twice: - **Nobody is told it changed.** Compose tracks reads of *snapshot state* objects only. Incrementing an ordinary `Int` in a click handler records nothing, so no recomposition is scheduled and the `Text` keeps showing `1`. - **It does not survive a rerun.** If the function recomposes for some other reason, the line `var quantity = 1` executes again and the local starts over. ## What `mutableStateOf` adds: observable state `mutableStateOf(value)` returns a `MutableState<T>`, a single-value holder whose reads and writes go through Compose's **snapshot system**. - When a composable reads `.value` during composition, the runtime records that the current **recompose scope** depends on it. - When code later writes a different value, the runtime schedules every scope that read it to recompose. Scopes that never read it are not scheduled. - What counts as "different" is decided by a `SnapshotMutationPolicy`. The default is `structuralEqualityPolicy()`, which compares with `==`; `referentialEqualityPolicy()` compares identity and `neverEqualPolicy()` treats every write as a change. For primitives there are specialised factories: `mutableIntStateOf`, `mutableLongStateOf`, `mutableFloatStateOf` and `mutableDoubleStateOf` avoid boxing on every read and write. Observability alone is not enough. If you write `val quantity = mutableStateOf(1)` directly in the function body, each recomposition executes that line again and creates a **new** state object holding `1`. The click that triggered the recomposition is lost the moment it takes effect. Compose's lint check `UnrememberedMutableState` flags exactly this. ## What `remember` adds: a slot in the Composition `remember { calculation }` runs the lambda during the first composition, stores the result in the **Composition** (the runtime's record of the UI tree) at that call site, and returns the stored object on every recomposition. The value is forgotten when the composable that called `remember` leaves the Composition, for example when an `if` stops emitting it. `remember` can hold anything, mutable or not, which is also why it is used to cache expensive objects. But a remembered plain object is still not observed: `remember { arrayOf(1) }` keeps the array, and changing its contents still schedules nothing. ## Putting the two together | Declaration | Survives recomposition | Writes trigger recomposition | |---|---|---| | `var q = 1` | no | no | | `val q = mutableStateOf(1)` | no, recreated each time | yes, but the new object resets | | `val q = remember { arrayOf(1) }` | yes | no | | `var q by remember { mutableIntStateOf(1) }` | yes | yes | ```kotlin @Composable fun QuantityStepper() { var quantity by remember { mutableIntStateOf(1) } Row { Button(onClick = { if (quantity > 1) quantity-- }) { Text("-") } Text("Qty: $quantity") Button(onClick = { quantity++ }) { Text("+") } } } ``` Three declaration forms are equivalent: `val state = remember { mutableStateOf(x) }`, the property delegate `var value by remember { mutableStateOf(x) }` (it needs the `getValue` and `setValue` imports from `androidx.compose.runtime`), and the destructured `val (value, setValue) = remember { mutableStateOf(x) }`. ## What counts as a write Recomposition is scheduled by **assigning** the state's value, not by changing an object the state happens to point at. That produces the most common bug on checkout screens: 1. The cart is held as `mutableStateOf(mutableListOf<CartItem>())`. 2. A click calls `cart.value.add(item)`. 3. The list changes in place, `.value` is never assigned, and nothing recomposes. Two fixes work. Hold a read-only `List` and assign a new one (`cart = cart + item`), so the write goes through the state. Or use `mutableStateListOf()`, whose `add` and `remove` are themselves snapshot writes. Compose lint reports the first pattern as `MutableCollectionMutableState`. ## What `remember` does not do `remember` lives exactly as long as its place in the Composition. When the activity is recreated by a rotation, the Composition is rebuilt and remembered values start over. Keeping a value across activity recreation and process death is `rememberSaveable`'s job, a separate API with its own rules.

  • The cart is `mutableStateOf(mutableListOf<CartItem>())` and a click calls `cart.value.add(item)`. Why does the cart row not update, and how do you fix it?
    `add` mutates the list object in place; the state's `.value` is never assigned, so no snapshot write is recorded and no reader is scheduled. Either keep a read-only `List` and assign a new one (`cart = cart + item`), or hold the items in `mutableStateListOf()`, whose `add` and `remove` are snapshot writes. Compose lint calls the original pattern `MutableCollectionMutableState`.
  • Why does Compose lint warn on `val total = mutableStateOf(0)` written straight in a composable body?
    That is the `UnrememberedMutableState` check. Without `remember`, each recomposition runs the line again and creates a new `MutableState` holding `0`, so any write is discarded on the very recomposition it triggers. Wrap it in `remember { }`, or move the state into a holder that lives outside the function body.
  • Why reach for `mutableIntStateOf` instead of `mutableStateOf(0)` for a counter?
    `mutableStateOf<Int>` holds its value as an object, so each `Int` written is autoboxed.`mutableIntStateOf` returns a `MutableIntState` that stores a primitive, exposes `intValue`, and still supports `by` delegation. An optional lint inspection, `AutoboxingStateCreation`, suggests the swap.

A plain local is a number chalked on a whiteboard that is wiped and redrawn on every refresh. remember pins a card to the board's frame so it outlasts the redraw. mutableStateOf puts a bell on the card that rings for everyone who looked at it when someone writes a new number.

  • mutableStateOf on its own keeps its value between recompositions
  • remember makes a value observable, so changing it updates the UI
  • Calling add on a mutable list held inside mutableStateOf recomposes the screen
  • Every write to a MutableState recomposes its readers, even an equal value
  • remember keeps the value across rotation and process death
  • Any state change recomposes the whole screen, not just the readers
open as a page

In Jetpack Compose, why does a checkout promo code survive rotation with `rememberSaveable` but not with `remember`, and how do you save a custom type?

level: middleimportance: must knowfreq 72%

basics

~20 s

remember lives in the Composition, which is rebuilt when the activity is recreated, so its value is lost. rememberSaveable also writes the value into saved instance state, restoring it after rotation and system-initiated process death; other types need @Parcelize or a Saver.

open as a page

In Jetpack Compose, how do you hoist a checkout promo-code field's state so the field composable becomes stateless, and what does the caller gain?

level: middleimportance: must knowfreq 75%

basics

~20 s

Move the remembered value out of the field and replace it with two parameters: the current value and an onValueChange-style callback. The caller then owns the single source of truth, can share it with the price summary, and can intercept or reject each edit.

open as a page

In Jetpack Compose on Android, how does `collectAsStateWithLifecycle` differ from `collectAsState` when a checkout screen collects a live price-summary Flow?

level: middleimportance: should knowfreq 62%

basics

~20 s

collectAsState collects for as long as the composable is in the composition, even while the app sits in the background. collectAsStateWithLifecycle stops collecting when the lifecycle drops below minActiveState, STARTED by default, and resumes above it, so Android screens should prefer it.

open as a page

In Jetpack Compose, when should a checkout screen compute a value with `derivedStateOf` instead of `remember` with keys, and when is `derivedStateOf` wasted or wrong?

level: seniorimportance: should knowfreq 55%

basics

~20 s

Use derivedStateOf when fast-changing state feeds a result that changes rarely, such as a scroll offset that only flips a show-total flag; readers recompose only when the result changes. Use remember with keys when inputs and output change together.

open as a page

As the Android lead on a Jetpack Compose codebase, what rule would you set for where UI state lives: in composables, plain state holder classes or screen-level state holders?

level: principalimportance: should knowfreq 40%

basics

~20 s

Keep simple UI element state in the composable that uses it, hoisted only to the lowest common ancestor; put complex UI logic in a remembered plain state holder; keep screen UI state and business logic in a screen-level holder, passing values and lambdas down.

open as a page