2

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?

1 Answer 1

5

It's because the composable function is now "stateless", meaning it will not change anything in its scope.

It's simple because:

  1. For every input, the function has the same output (since it only relies on its inputs and does not change anything on the outside).

  2. It becomes very testable (because of 1).

  3. 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.