Pick the fix
You want to preview and reuse this counter in two screens. What's the best change?
@Composable
fun Counter() {
var count by remember { mutableStateOf(0) }
Button(onClick = { count++ }) { Text("Count: $count") }
}Hint 1 of 1
Who should own the count?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A Make it take count: Int and onIncrement: () -> Unit and move the state to the caller
Correct. That's state hoisting: the counter becomes stateless and reusable.
Why not the others?
- B Pass the screen's ViewModel into it. That ties the counter to one ViewModel type and breaks previews.
- C Make
counta global variable. Global state is shared by every caller and isn't observable. - D Switch to
rememberSaveable. That changes how long the state lives, not who owns it.