Sitemap

States in Jetpack Compose. Easy!

3 min readMar 29, 2023

--

Press enter or click to view image in full size

Hi 👋

If you recently started working with Jetpack Compose and wrote your first layout, you must’ve stumbled upon this question, “How do I update a view in the layout?”. I’ll try to answer that with an example, hitting that button should update the count in the text above.

Normally you would write 2 files, one XML layout and one Kotlin class and use the setter exposed on the TextView to update it.

Once done, we ask existential questions like “Should the button directly update the text? We should find a way to decouple them using an architecture pattern”.

With Compose because there is no XML, we can ask the Text to take the value from the variable count and the button will simply update count whenever it is clicked. And once you hit the button, nothing happens 😆

💡 This brings us to the last part where we use states to bring everything together.

State in an app is any value that can change over time. Any time a state is updated a recomposition takes place. ~ Android Developer Docs

When you declare that count is a mutable state, compose UI system will re-render the Views which depend on that state. This is called recomposition, but to prevent the state from resetting itself in case the composable which holds it becomes a part of the recomposition cycle, we use the remember keyword which will preserve its value across recomposition cycles. And that gives us the result!

My favourite part here is that there is not need to fiddle around with getters and setters for the properties of a View, write your layout once and now all you need to control are the states, how clean!🌟

This was a crisp write up based on information from topics I am working on currently, there will be more of these coming in the future so make sure you follow!

--

--