DEV Community

Maria Luíza
Maria Luíza

Posted on

State With Jetpack Compose

Gif of a cat vampire

Hello, fantastic person on the internet! Hope you're doing well.

When migrating from XML to Compose, it can be difficult to understand certain concepts.

 

State

There is no way to update the UI after it has been drawn. What you can control is the state of your UI. When UI state changes, Compose reconstructs the components of the UI that have been altered.

 

Unidirectional Data Flow

Since composables accept states and expose events, the unidirectional data flow (UDF) pattern aligns perfectly with Jetpack Compose.

The UDF is a design pattern in which state flows downward and events flow upward.

Photo showing the flux of the UDF

 

Functions

To declare a variable for controlling the state of a UI component, we need to understand certain functions:

  • remember
  • rememberSaveable
  • mutableStateOf()

mutableStateOf() is an observable type for Compose. Used when the value can change at some moment.

remember assists in retaining state throughout recompositions. However, the state is not preserved during configuration changes.

**rememberSaveable **is very similar to remember. It automatically saves any value that can be stored in a Bundle.

 

Alright, how can we observe that in practice?

Imagine that we have a text field where the value can change depending on the user type. 

To effectively work with this component, we can utilize state.
Declare a variable responsible for capturing the value of our component:

Now, let's simply assign the variable to receive the value from the text field:

This enables us to capture the variable of whatever the user types. Even if they change the value, since we are constantly updating the value of the text it doesn't matter.

As a result, things like TextField don't automatically update like they do in imperative XML based views.

 

Conclusion

By combining a declarative UI paradigm with efficient state handling and architecture patterns, Jetpack Compose empowers developers to create apps that are not only visually stunning but also robust, maintainable, and future-ready. 

Embracing Jetpack Compose is not just a technological choice, but a strategic one that propels Android app development into a more innovative and efficient direction.

Happy coding ❤


Please let me know what you think in the comments…

Connect with me 👇

Linkedin

GitHub

Instagram

Twitter

Medium

Gif of a mushroom

Top comments (1)

Collapse
 
4gus71n profile image
Agustín Tomas Larghi

I like these little digestible posts! I'd love to see a follow-up post with more things like rememberSaveable and how to pre-fill default values in TextFields