State and Recomposition

Android Development Fundamentals with Compose

Course 4 ยท Chapter 4 ยท Why the Screen Changes

This is the most important idea in Compose. In XML you change the screen by finding a view and telling it what to show. In Compose you never touch the UI directly: you change state (a value your composables read), and Compose recomposes, that is, calls the affected composables again so the screen matches the new value. Master this and everything else in Compose follows from it.

What was checked, and how: read this first
Checked in the docs (one web search, summaries only): remember and mutableStateOf, recomposition triggered by writing state, why remember is needed, rememberSaveable and configuration changes, and state hoisting with stateless and stateful composables. Thin in the docs I found: mutableStateListOf (only a performance note). General knowledge, not checked: the details of how the compiler tracks reads, and the list example. All code is unrun (no Kotlin compiler on the machine used to write this); the import lines are given so you can check them. Nothing was seen on your install.

State, and the Bug Without It

Here is the mistake almost every beginner makes. The variable changes when you tap, but the screen does not, because nothing told Compose to look:

@Composable fun BrokenCounter() { var count = 0 // plain variable: Compose is not watching it Button(onClick = { count++ }) { Text("Clicked $count times") // never redrawn, and reset if redrawn for another reason } }

(docs) A local mutableStateOf without remember is recreated on every pass, because recomposition can happen at any time and calls the composable again, resetting the value. The fix has two parts: mutableStateOf makes a value Compose can watch, and remember keeps it between recompositions.

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 Counter() { var count by remember { mutableIntStateOf(0) } // state Compose watches and keeps Button(onClick = { count++ }) { Text("Clicked $count times") } }
PieceWhat it does
mutableIntStateOf(0)Creates an observable Int holder starting at 0 (general knowledge: the primitive version of mutableStateOf).
remember { ... }(docs) Stores the object in memory in the composition and forgets it when the composable leaves the screen.
by (with getValue, setValue)Lets you write count and count++ instead of count.value.
count++(docs) Writing to the state schedules recomposition of every composable that read it.

What Recomposition Is

When state changes, Compose calls again the composables that read it (docs), and only those (general knowledge). Your composable is therefore a function from state to UI: same state, same screen. Two consequences:

  • A composable may run many times, and at any time, so keep it free of slow work and surprises. Chapters 5 onward show where events and side effects belong.
  • remember lasts while the composable stays on screen. To keep a value across rotation you use rememberSaveable (docs: it saves the state in a Bundle), as in Chapter 2.

State Hoisting: Stateless and Stateful

(docs) State hoisting means moving state up to the caller so the composable below becomes stateless: it receives a value and a callback instead of owning the state. The shape is always: value down, events up.

// Stateless: gets the value and an event callback; owns nothing @Composable fun CounterButton(count: Int, onIncrement: () -> Unit) { Button(onClick = onIncrement) { Text("Clicked $count times") } } // Stateful: owns the state and passes it down @Composable fun CounterScreen() { var count by remember { mutableIntStateOf(0) } CounterButton(count = count, onIncrement = { count++ }) }
StatelessStateful
Owns the state?No: it receives the value and a callbackYes: it holds remembered state
ReuseEasy: any caller can supply the stateHarder
Preview and testEasy: pass any valueAwkward
Typical homeMost of your composablesA screen or a few top-level pieces

Prefer stateless composables and keep the state in as few places as possible (general knowledge, and the usual Compose advice). The two counters in Exercise 2 show why: when one parent owns both values it can also show their total.

Lists in State

(general knowledge; the docs I found said little about it) To change a list on screen you need a list Compose can watch. mutableStateListOf gives one whose changes (add, remove) trigger recomposition. The one source on it that I found notes that it tracks each element's changes individually, so it has a cost; Chapter 6 returns to lists and LazyColumn.

@Composable fun ShoppingList() { val items = remember { mutableStateListOf("Milk", "Eggs") } Column { Button(onClick = { items.add("Item ${items.size + 1}") }) { Text("Add item") } items.forEach { item -> Text(item) } } }

Compared with the XML Way

Views (Android Development Fundamentals)Compose
Update the screenFind the view and call setText, setVisibilityChange state; the UI is recomposed
Source of truthSpread between views and variablesThe state; the UI is derived from it
Forgetting to update a viewA common bug: the screen shows old dataNot possible for state-driven UI; the common bug is a plain variable that is not state
Keep across rotationonSaveInstanceStaterememberSaveable
Compared with the Classic UI course
Android Development Fundamentals has no chapter like this one, because with Views you changed the screen by hand. State is the main new idea, and the next chapters (input, lists, navigation) all rely on it.

Try It Yourself

Exercise 1

Type in BrokenCounter and run it. Describe what happens when you tap. Then fix it with remember and mutableIntStateOf, and explain in a sentence why the first version failed.

๐Ÿ“„ View solution
Exercise 2

Using the stateless CounterButton, build TwoCounters: two independent counters in one parent that also shows their total. Say which composable owns the state.

๐Ÿ“„ View solution
Exercise 3

Make a Switch that shows the text "On" or "Off", keeping its value across rotation. Then switch rememberSaveable to remember and rotate the device to see the difference.

๐Ÿ“„ View solution
Not Yet Verified
Checked in the docs (one web search, summaries only): remember and mutableStateOf; that writing state schedules recomposition; that remember forgets when the composable leaves the composition; rememberSaveable and Bundles; state hoisting with stateless and stateful composables; the note that mutableStateListOf tracks elements individually.
Not verified: that only affected composables rerun; how mutableStateListOf is meant to be used (not found); mutableIntStateOf as the primitive form (general knowledge); the "prefer stateless" advice (general knowledge); the XML comparison column; the imports; every listing and solution (unrun); the exercises (not run by me). Nothing was checked on your install.
Sources: State and Jetpack Compose (developer.android.com), State in Jetpack Compose (developer.android.com codelab), Intro to state in Compose (developer.android.com codelab).
Coming up
Chapter 5 covers user interaction: click handlers, TextField input, simple gestures, Intents and passing data to another screen. It builds directly on the state you met here.