Jetpack Compose — UI as Functions
In older Android code, updating Sprout's "watered 3 times" label meant finding the label view and changing its text by hand. Forget one update and the screen lies. Jetpack Compose removes that whole class of bug by flipping the approach: you describe what the screen should look like, and Compose keeps it in sync.
The rule
UI is a function of state; change the state, not the screen.
A composable is a Kotlin function marked @Composable that describes part of the UI:
@Composable
fun WateringCount(count: Int) {
Text(text = "Watered $count times")
}Key facts:
- Composables emit UI; they do not return views. Their return type is
Unit. - By convention, their names are PascalCase nouns, like
PlantCard, because they read like UI elements. - They can only be called from other composables, or from
setContent. - When state a composable reads changes, Compose calls it again. This is recomposition, and Compose only reruns the parts that depend on the changed state.
Because a composable may run many times, and in any order, it must be free of side effects: no saving files or starting network calls inside it.
@Preview lets you see a composable in Android Studio without running the app:
@Preview
@Composable
fun WateringCountPreview() { WateringCount(count = 3) }The shortcut
For any UI change, ask "what state changed?" Update that; never reach into the screen.
Old habit
Find the label, call
setText. Compose has no such step.
Drills
Answer fast — trust the rule.
What marks a Kotlin function as a composable?
In Compose, how do you make a label show a new value?
What is recomposition?
Why should a composable not save data to a database directly in its body?
Remember
- UI is a function of state; change the state, not the screen.
- Composables are
@Composable, returnUnit, and are named like UI elements. - Recomposition can happen often, so keep composable bodies free of side effects.
