Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Other state management options that I may use with Jetpack Compose, beyond State hoisting?

I am learning Jetpack compose, and I have been seen so far that lifting the state up to a composable's caller to make a composable stateless is the way to go. I`ve been using this pattern in my Compose apps.

For an app state that I need to modify from many different places of the tree, I will have to pass around a lot of callbacks, This can become difficult to manage.

I have some previous experience with Flutter. The way Flutter deals with providing a state to its descendants in the tree to overcome the above, is to use other mechanisms to manage state, namely Provider + ChangeNotifier.

Basically, with Provider, a Provider Widget is placed in the tree and all the children of the provider will have access to the values exposed by it.

Are there any other mechanisms to manage state in Jetpack Compose apps, besides State hoisting? And, what would you recommend?

like image 528
lbarqueira Avatar asked Sep 02 '25 15:09

lbarqueira


1 Answers

If you need to share some data between views you can use view models.

@Composable
fun TestScreen() {
    val viewModel = viewModel<SomeViewModel>()
    Column {
        Text("TestScreen text: ${viewModel.state}")
        OtherView()
    }
}

@Composable
fun OtherView() {
    val viewModel = viewModel<SomeViewModel>()
    Text("OtherScreen text: ${viewModel.state}")
}

class SomeViewModel(savedStateHandle: SavedStateHandle): ViewModel() {
    var state by savedStateHandle.saveable { mutableStateOf(UUID.randomUUID().toString()) }
}

The hierarchy topmost viewModel call creates a view model - in my case inside TestScreen. All children that call viewModel of the same class will get the same object. The exception to this is different destinations of Compose Navigation, see how to handle this case in this answer.

You can update a mutable state property of view model, and it will be reflected on all views using that model. Check out more about state in Compose.

The view model lifecycle is bound to the compose navigation route (if there is one) or to Activity / Fragment otherwise, depending on where setContent was called from.

like image 121
Philip Dukhov Avatar answered Sep 05 '25 06:09

Philip Dukhov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!