Reputation: 119
This tutorial on state hoisting in jetpack-compose says:
By passing a function and not a state to OnboardingScreen we are making this composable more reusable and protecting the state from being mutated by other composables. In general, it keeps things simple.
How does passing a callback function achieve these stated goals any better than passing the state directly?
Upvotes: 2
Views: 1220
Reputation: 4060
It's because the composable function is now "stateless", meaning it will not change anything in its scope.
It's simple because:
For every input, the function has the same output (since it only relies on its inputs and does not change anything on the outside).
It becomes very testable (because of 1).
It gives the power to anyone that is using it. They can "change" the state however they want. Imagine a TextField(text: String, onTextChanged: (text: String) -> Unit)
. You can change the state however you want (for example, remove any digits from the string and then apply it to your state). If TextField
handled the state itself, It would always change the state to the actual text (and you would need another mechanism for the said scenario).
This brings a simplicity to your composable as you do not have to worry about how your composable (e.g. TextField
) changes a state.
Upvotes: 5