Thinking in Compose
Why it matters
- Compose is a different model, not new syntax for Views. If you keep the View habits, you fight the framework.
- Most early Compose bugs come from one wrong belief: "my function runs once, in order, like
onCreate". It does not. - "Explain declarative UI" and "what is recomposition" are standard questions in Android interviews now.
- Every later topic (state, hoisting, side effects, performance) is built on this model.
The simple explanation
Think of a restaurant order slip. The kitchen never edits a half-cooked dish when you change your mind. It reads the new slip and produces the dish that matches it.
- With Views you are the cook who edits: find the
TextView, callsetText, show or hide theProgressBar. You must remember every step. - With Compose you only write the slip: "given this state, the screen looks like this". The runtime works out the changes.
- The formula: UI = f(state). Same state in, same UI out.
The real names:
| Idea | What it means |
|---|---|
| Composable | A function marked @Composable that describes a piece of UI. It does not return a View. |
| Composition | The tree of composables Compose built on the first run. |
| State | A value that Compose watches. When it changes, the UI that read it is invalidated. |
| Recomposition | Running the affected composables again with the new state. Compose updates the tree. |
| Unidirectional data flow | State flows down as parameters. Events flow up as lambdas. |
Each frame goes through three phases: composition (what to show), layout (where it goes) and drawing (how it looks). A state change re-runs only the phases that read it.
Rules a composable must follow, because the runtime is free to:
- Run it often. An animation can recompose it every frame.
- Skip it. If its inputs did not change, Compose may not call it at all.
- Run composables in any order, and possibly in parallel on other threads in the future.
- Cancel a recomposition and start again if the state changes again.
So a composable body should only describe UI. It should not start requests, write to shared variables or count things.
Notes
- UI = f(state). Do not "update" the UI. Change the state and let Compose redraw.
- A composable returns
Unit. It emits UI into the composition instead of returning a view object. - Recomposition is not a full redraw. Compose re-runs only the composables that read the changed state and skips the rest.
- A composable can run many times per second. Keep the body cheap and free of side effects.
- Do not rely on call order or on a call happening at all. Never depend on "this ran before that".
- Side effects (network calls, analytics, registering listeners) belong in effect APIs such as
LaunchedEffect, or in the ViewModel. They are covered in a later lesson. - State flows down, events flow up. The composable that shows a value does not own it.
- A state read in a lambda such as
Modifier.offset { }ordrawBehind { }happens in the layout or draw phase and can skip composition. - On Android, Compose still lives inside an Activity (or a Fragment).
setContentis the entry point. - Recomposition internals, stability and skipping rules are an Advanced lesson. Here you only need the model.
Code example
One field and one greeting. The text is state. The UI is a pure description of it.
@Composable
fun GreetingScreen(modifier: Modifier = Modifier) {
// State: Compose watches this value.
var name by remember { mutableStateOf("") }
Column(modifier.padding(16.dp)) {
OutlinedTextField(
value = name,
// Event goes up: we change the state, Compose redraws.
onValueChange = { name = it },
label = { Text("Your name") },
)
// The UI is a function of `name`. No setText, no setVisibility.
if (name.isBlank()) {
Text("Type your name")
} else {
Text("Hello, $name")
}
}
}Typing changes name. Compose re-runs the parts that read name and updates the tree. There is no code that "removes the old text".
Run the idea in plain Kotlin
Compose cannot run in the browser, but the rule can. A render function that depends only on its input gives the same output every time. That is what makes skipping and re-running safe.
data class UiState(val name: String)
fun render(state: UiState): String =
if (state.name.isBlank()) "Type your name" else "Hello, " + state.name
fun main() {
var state = UiState("")
println(render(state)) // Type your name
state = state.copy(name = "Asha") // the only thing we change is state
println(render(state)) // Hello, Asha
println(render(state)) // same state, same output
}In production
- The product team saw far more "screen viewed" events than real sessions.
- A developer had logged the event directly in the body of the composable.
- Cause: the body runs on every recomposition, not once per screen visit. Typing, animations and list updates each triggered it again.
- Reproduce it. Add a log line in the body and type in a text field. The log repeats on every key press.
- Move one-time work out of the body:
LaunchedEffect(Unit) { analytics.screenViewed() }, or send the event from the ViewModel when the screen state is first produced. - Treat any line in a composable that "does something" as a bug until proven otherwise.
- Layout Inspector in Android Studio shows recomposition counts per composable. A count that climbs while the user does nothing is a signal.
- A screen kept a
var isLoading = falsein the composable body and set it totruebefore a request. - The spinner did not appear when the request started.
- Cause: a plain variable is not observable, so changing it does not trigger recomposition. It is also reset to
falseon every run of the function. Compose had nothing to watch.
- Hold the value in Compose state (
mutableStateOf) or expose it from the ViewModel as aStateFlowand collect it. - Rule of thumb: if the UI depends on a value that changes, that value must be state.
Common mistakes
- Treating the composable body as
onCreate. It is not run once. Put one-time work in an effect or the ViewModel. - Using a normal
varfor something the UI shows. Compose cannot observe it, so the screen never updates. - Trying to "refresh" the screen by hand. There is no refresh call. Change the state and Compose updates only what changed.
- Assuming siblings run in order. Do not make one composable depend on a value another one wrote during composition.
- Doing heavy work in the body, such as sorting a big list or parsing JSON. It repeats on every recomposition. Move it to the ViewModel or wrap it in
remember. - Mixing the two worlds without a plan. A screen half in Views and half in Compose still needs one clear owner for each piece of state.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What does declarative UI mean in Compose?”
“What is recomposition?”
“Why must a composable have no side effects in its body?”
“How is state different from a normal variable in a composable?”
Quiz
A composable function body contains a network call. What is the most likely result?
Which statement about recomposition is correct?
What does UI = f(state) mean for how you write code?
In unidirectional data flow, how do events travel?
0 of 4 answered
Mini task
Build a screen with a text field and a counter that shows how many times the screen function has run.
- Add a plain
var runs = 0in the composable body, increment it and show it. Type in the field and watch. Explain why it behaves oddly. - Replace it with a log line (
Log.d("Compose", "GreetingScreen ran")) and look at Logcat while typing. - Move one "pretend analytics" log into
LaunchedEffect(Unit)and compare how often it prints.
You are done when you can say, in one sentence each, why step 1 misleads, why step 2 prints so often and why step 3 prints once.