Component - remember and mutableStateOf
This UI component shows a simple counter with a button. It uses remember and mutableStateOf to keep track of the number. When you tap the button, the number increases and the screen updates automatically.
This UI component shows a simple counter with a button. It uses remember and mutableStateOf to keep track of the number. When you tap the button, the number increases and the screen updates automatically.
Column ├── Text └── Button
remember in Jetpack Compose?rememberremember keeps a value alive during recompositions to avoid resetting.count initialized to 0 using remember and mutableStateOf?remember wraps mutableStateOf to keep state across recompositions.val count = remember { mutableStateOf(0) }. Others misuse function calls or syntax.var count = remember { mutableStateOf(0) }
count.value += 1
println(count.value)What will be printed after this code runs once?count is a mutable state holding 0 initially.count.value += 1 increases value to 1, so printing count.value outputs 1.var count = mutableStateOf(0)
count = remember { mutableStateOf(1) }remember can only be called inside a composable function context.remember called outside composable, which is invalid.remember { mutableStateOf(0) } with var count by delegates state correctly.count++ updates state and triggers UI recomposition.remember, so state resets on recomposition. @Composable
fun Counter() {
var count = 0
Button(onClick = { count++ }) {
Text("Count: $count")
}
}
uses simple var without state, so UI won't update. @Composable
fun Counter() {
val count = remember { 0 }
Button(onClick = { count++ }) {
Text("Count: $count")
}
}
remembers an Int, not mutable state, so increment fails.Pass the test and this pattern moves unknown