In Jetpack Compose, why does a quantity counter kept in a plain local `var` never update, and what do `remember` and `mutableStateOf` each fix?
answer
- observed versus kept
- a write reschedules whoever read it
- recomposition re-runs the function body
- stored in the Composition, forgotten on exit
- equal writes are not changes
basics
~20 sA 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 sCompose 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 linesimport 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
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.
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.
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.
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