State and Recomposition
State drives the UI
“State” is data that can change over time. When state changes, Compose re-runs your function and updates the screen.
@Composable
fun Counter() {
var count by remember { mutableStateOf(0) }
Column {
Text("Count: $count")
Button(onClick = { count++ }) {
Text("Add one")
}
}
}
mutableStateOf(0)— creates observable state.remember— keeps the value across recompositions.- Tapping the button changes
count, so theTextredraws automatically.
Hoist your state: For reusable components, pass state in and send events out (“state hoisting”) instead of keeping it inside.