Junior — Middle
What methods can be used to save and manage the state of the user interface in Jetpack Compose?
sobes.tech AI
Answer from AI
In Jetpack Compose, the state of the user interface can be saved and managed in several ways:
- remember — saves the state within the composition. When the UI is recreated, the value is preserved as long as the composition is active.
var count by remember { mutableStateOf(0) }
- rememberSaveable — similar to remember, but additionally saves the state during configuration changes (e.g., screen rotation).
var text by rememberSaveable { mutableStateOf("") }
- ViewModel — for more complex and long-lived state, which is preserved when the Activity or Fragment is recreated.
class MyViewModel : ViewModel() {
var count by mutableStateOf(0)
}
@Composable
fun MyScreen(viewModel: MyViewModel = viewModel()) {
Text("Count: ${viewModel.count}")
}
- State hoisting — the state is lifted higher up the component hierarchy and passed through parameters, which improves testability and reusability.
These methods allow effective management of UI state, ensuring its preservation and reactivity.