Android Beginners

Lesson 12: State in Compose: remember and mutableStateOf

Ahmad Najar Ahmad Najar 1 min read

State in Compose: remember and mutableStateOf

This is the most important lesson in the entire course. Everything from here forward depends on understanding this properly.

The core idea

In Compose, the UI is a direct reflection of your app's current state. When state changes, Compose automatically re-runs (recomposes) whatever part of the UI depends on it — you never manually update a screen element yourself.

mutableStateOf — a value Compose watches

var count by remember { mutableStateOf(0) }

Button(onClick = { count++ }) {
    Text("Clicked $count times")
}

Every time count changes, Compose knows exactly which Text depends on it and redraws only that — you never write text.setText(...) or anything like it.

Why "remember" is needed

Composable functions can re-run frequently. Without remember, a new mutableStateOf(0) would be created every single time, resetting your count back to zero constantly. remember tells Compose: "keep this same state object alive across recompositions."

What remember does NOT protect against

var count by remember { mutableStateOf(0) }
// This resets to 0 if the screen rotates!

remember survives normal recomposition, but not a full Activity recreation (which happens on rotation, by default). For state that needs to survive that, you'd use rememberSaveable instead — swap it in and rotation-safety comes for free:

var count by rememberSaveable { mutableStateOf(0) }

The pattern you'll use forever

var taskName by remember { mutableStateOf("") }

TextField(value = taskName, onValueChange = { taskName = it })
Text("You typed: $taskName")

State goes in, gets displayed, gets updated by user interaction, which changes the state, which updates the display again. This loop — state → UI → interaction → new state — is Compose in one sentence.

Next: Lesson 13 — building a real, fully interactive counter screen from scratch.

Android Beginners