State and remember

You will understand how Compose tracks state reads to decide which composables recompose, and when to use remember, rememberSaveable, and derivedStateOf. About 25 minutes.

Why it matters

  • Many Compose performance problems come from reading state in a wider scope than needed. Knowing the mechanism lets you fix it instead of guessing.
  • Interviewers ask 'what recomposes when X changes?' and expect you to explain that Compose records state reads and re-runs only the scopes that read the changed value.
  • Choosing remember where you needed rememberSaveable loses UI state on rotation, a common complaint in Compose apps.
  • derivedStateOf stops a screen from recomposing on every scroll frame when it only cares whether a threshold was crossed.

The simple explanation

  • A composable is a recipe card: the kitchen can run it many times, skip it, or run it out of order.
  • remember is a sticky note on the card: the value survives the next time the card is read, but not if the kitchen is cleaned (rotation).
  • mutableStateOf is a whiteboard in the kitchen: anyone who looks at it is noted; when someone writes a new number, only those who looked get called back.
  • rememberSaveable is a sticky note that also gets photographed before the kitchen is cleaned, so it survives.
  • derivedStateOf is a sign that says 'OPEN' or 'CLOSED' based on a counter: the sign only changes when the counter crosses the threshold, not on every tick.

In Compose, a composable is a plain function. It can run many times, be skipped, or run in a different order. A local var is created again on every run. To keep a value between runs, the composable must remember it (or get it from a state holder such as a ViewModel).

State and recomposition. A MutableState<T> (created by mutableStateOf) is observable. During composition, Compose records which recompose scopes read its .value. When you write a new value, Compose invalidates exactly those scopes and re-runs them. A scope that re-runs calls its children again, but a child whose arguments did not change is skipped. So where you read state decides what re-runs, not where you declare it. Try both options in the simulator below.

Typed variants. mutableIntStateOf, mutableLongStateOf, mutableFloatStateOf and mutableDoubleStateOf avoid boxing primitives. Prefer them over mutableStateOf(0) for those types.

remember vs rememberSaveable.

FunctionSurvives recompositionSurvives rotation and system-initiated process death
rememberYesNo
rememberSaveableYesYes (saved in the saved instance state Bundle)

Neither survives the user swiping the app away or the composable leaving the composition for good.

Stateless composables. A composable that takes all data as parameters and holds no state of its own is stateless. When its parent recomposes with the same arguments, Compose can skip it. This is the "state down, events up" pattern.

derivedStateOf. Wraps a calculation over other state so that readers are notified only when the result changes. It pays off when the inputs change much more often than the result, such as "is the list scrolled past the first item?" while the scroll position changes every frame.

Try it: who recomposes?

Choose where the count is read, then add to it and watch the run counts.

  • Screenran 1×
  • Header()ran 1×
  • Counter(...)ran 1×
  • CountTextran 1×
  • AddButton(onClick)ran 1×

Screen reads count, so Screen runs again and passes the new value to Counter. Header and AddButton get the same inputs as before, so Compose skips them.

In the first option, Screen reads count, so Screen re-runs and passes the new value to Counter and CountText; Header and AddButton get the same inputs and are skipped. In the second option, only CountText reads the value (through a lambda), so it is the only scope that re-runs.

Notes

  • remember { } runs its lambda when the composable first enters composition; the result is stored and returned on every recomposition at the same position.
  • mutableStateOf(value) creates a MutableState<T>. Reading .value during composition records the current scope as a reader; writing .value invalidates those readers.
  • A scope that recomposes calls its children, but children with unchanged arguments are skipped. Reading state in a parent does not mean the whole subtree re-runs.
  • mutableIntStateOf, mutableLongStateOf, mutableFloatStateOf, mutableDoubleStateOf avoid boxing. Use them for those primitive types.
  • rememberSaveable { } behaves like remember but also saves the value in the saved instance state, so it survives rotation and system-initiated process death. The value must fit in a Bundle (primitives, String, Parcelable, Serializable and similar) or you provide a Saver.
  • For your own types, use @Parcelize, or a custom Saver such as mapSaver or listSaver. Saving a type that cannot go in a Bundle throws an exception; it does not fail silently.
  • Changing the key of remember(key) { } discards the old value and runs the lambda again. Use it to reset a remembered value when an input changes.
  • var x = 0 inside a composable body resets on every recomposition. Use var x by remember { mutableIntStateOf(0) } instead.
  • The by delegate needs import androidx.compose.runtime.getValue and setValue.
  • Reads inside callbacks and coroutines (an onClick, a LaunchedEffect block) are not composition reads, so they never cause recomposition. To react to state changes inside a coroutine, use snapshotFlow.
  • derivedStateOf must be wrapped in remember, otherwise a new derived state is created on every recomposition.

Code example

Two small composables. The first owns a count and passes it to a stateless child. The second uses derivedStateOf so the screen reacts only when the list crosses a threshold, not on every scrolled item.

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
 
// Stateful screen: owns the count
@Composable
fun CounterScreen() {
    var count by rememberSaveable { mutableIntStateOf(0) }
 
    Column {
        CountBadge(count)                                 // re-runs when count changes
        Button(onClick = { count++ }) { Text("Increment") } // same inputs: skipped
    }
}
 
// Stateless composable: no remember, no mutableStateOf
@Composable
fun CountBadge(count: Int) {
    Text("Count: " + count)
}
 
@Composable
fun MessageList(messages: List<String>) {
    val listState = rememberLazyListState()
 
    // firstVisibleItemIndex changes many times while scrolling;
    // showHint changes only when it crosses 0
    val showHint by remember {
        derivedStateOf { listState.firstVisibleItemIndex > 0 }
    }
 
    Box {
        LazyColumn(state = listState) {
            items(messages) { message -> Text(message) }
        }
        if (showHint) {
            Text("Newer messages above", Modifier.align(Alignment.TopCenter))
        }
    }
}
  • mutableIntStateOf avoids boxing the Int. rememberSaveable keeps the count across rotation.
  • CounterScreen reads count when it passes it to CountBadge, so CounterScreen and CountBadge re-run on each click. The Button gets equal inputs and is skipped (with strong skipping, the onClick lambda is remembered automatically).
  • In MessageList, the composable reads only showHint. Scrolling from item 3 to item 40 changes firstVisibleItemIndex many times, but MessageList recomposes only when showHint flips.
  • Without derivedStateOf, reading listState.firstVisibleItemIndex directly in the body would recompose MessageList every time the first visible item changes.

Run the idea in plain Kotlin

This models derivedStateOf: the input changes on every click, but readers are notified only when the result flips.

fun main() {
  var count = 0
  val threshold = 10

  // the derived value, and the last value readers were told about
  var showWarning = false

  for (click in 1..15) {
      count++
      val newWarning = count > threshold
      if (newWarning != showWarning) {
          showWarning = newWarning
          println("Click " + click + ": result changed to " + showWarning + ", readers recompose")
      } else {
          println("Click " + click + ": result still " + showWarning + ", readers not notified")
      }
  }
}

Expected output: clicks 1 to 10 print "result still false, readers not notified", click 11 prints "result changed to true, readers recompose", and clicks 12 to 15 print "result still true, readers not notified". Fifteen input changes, one notification.

In production

A toolbar that recomposed the whole screen on every scroll frame
  • A product detail screen stuttered on low-end devices. Layout Inspector showed the screen composable recomposing continuously while scrolling.
  • To fade in a toolbar title, the screen read listState.firstVisibleItemScrollOffset directly in its body.
  • That value changes on every scroll frame, so the screen scope re-ran on every frame, and so did every child whose arguments changed.
The fix
  • For the "show title" flag, the team used remember { derivedStateOf { listState.firstVisibleItemIndex > 0 } }, so the screen recomposes only when the flag flips.
  • For the smooth fade, they moved the read into the draw phase: Modifier.graphicsLayer { alpha = ... } reads the offset inside the lambda, which skips composition entirely.
  • Layout Inspector then showed the screen's recomposition count staying flat while scrolling.
Lost form step after rotation
  • Users reported that a multi-step onboarding form reset to step one after rotating the device.
  • The step index was stored with remember { mutableStateOf(0) }, which does not survive a configuration change.
  • Reports increased after a release that added a landscape layout.
The fix
  • The team replaced remember with rememberSaveable for the step index so it is saved in the instance state.
  • They added a test with StateRestorationTester, which simulates recreation and checks that saved state comes back.
  • The fix was one line, but the test found two other fields with the same issue.

Common mistakes

  • Using var x = 0 inside a composable body. The value resets on every recomposition, and Compose does not observe it. Use var x by remember { mutableIntStateOf(0) }.
  • Calling mutableStateOf outside remember. A new state object is created on every recomposition, so the value resets to its initial value each time and the UI seems never to change. Wrap it in remember { }. Android Lint flags this.
  • Using remember instead of rememberSaveable for user-visible UI state. The value is lost after rotation or process death. Use rememberSaveable for small UI state such as a form step or a selected tab. Large or business data belongs in a ViewModel or on disk.
  • Expecting a state read inside a coroutine to restart it. Reads in LaunchedEffect blocks and callbacks are not tracked by composition. Convert the state to a Flow with snapshotFlow { } and collect it.
  • Reading state higher than needed. The scope that reads a value re-runs on every change. Read fast-changing values as low as possible, or pass a lambda such as { count } so only the child that calls it reads the value.
  • Reading a high-frequency value when you only need a threshold. A scroll offset read in a body recomposes that scope on every frame. Wrap the check in derivedStateOf, or read the value in a layout or draw lambda.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“What happens when a mutableStateOf value changes?”

“When do you use rememberSaveable instead of remember?”

“Why use derivedStateOf?”

“What is "state down, events up"?”

Quiz

What does remember { mutableStateOf(0) } do?

Which of these survives a screen rotation?

What decides which composables re-run when a state value changes?

What is the main benefit of derivedStateOf?

0 of 4 answered

Mini task

Build a step counter with history.

  1. Create a @Composable function StepCounter() with var step by rememberSaveable { mutableIntStateOf(0) }.
  2. Add var history by remember { mutableStateOf(listOf<Int>()) }.
  3. Add val isHigh by remember { derivedStateOf { step > 5 } } and show a warning Text when isHigh is true.
  4. Add a Button that increments step and appends the new value to history (history = history + step).
  5. Render the history as a Column of Text items, one per entry.
  6. Rotate the device (or trigger a configuration change in the emulator).

Done when: after rotation the step number is preserved (because of rememberSaveable), the history list is empty (because remember does not survive rotation), and the warning text appears when the step is above 5.

Next: State hoisting