Stateful and Stateless composables - devrath/ComposeAlchemy GitHub Wiki
Difference between Stateful and stateless composables
Stateful |
Stateless |
---|---|
A composable function that keeps its state is called a stateful composables | A composable function that does not keep its state is called stateless composables |
When do you want your composables to be stateless?
- In most cases, We want the composables to remain stateless.
- And usually the state of the entire screen is calculated in one place. Basically in the
view-model
itself, it's calculated. - Then from the ViewModel it is passed down to all the composables.
- This makes testing the composables much easier when we can test all the composables from one place instead of jumping to multiple composables as needed.
Example for the stateless composable
Here you can see the CustomButton
relies on the caller to pass the label so thus the state is not kept here in the composable itself instead, the parent passes the label in the hierarchy.
@Composable
fun CustomButton (
label: String, onClick:()-> Unit
) {
Button(onClick){
Text(text = label)
}
}
When do you want your composables to be stateful?
- Your screen-level composable, One responsible for rendering the entire children's composables is a good candidate for a stateful composable.
Example for the stateful composable
@Composable
fun FlowsDemo (navController: NavHostController) {
val viewModel: FlowsDemoVm = hiltViewModel()
val state by viewModel.state
}