Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 104 ยท Jetpack Compose Fundamentals

Thinking in Compose

Learn the Jetpack Compose mindset: declarative UI versus Views, the composition tree, why UI is made of functions, how setContent starts it and how previews work.

For about a decade, Android screens were built from XML layout files plus code that held references to each view and changed it by hand. Jetpack Compose, the modern UI toolkit, asks you to think differently: instead of changing the screen, you describe it. You write functions that take data and say what the UI looks like for that data. When the data changes, Compose runs the relevant functions again and updates the screen.

This lesson is about that mental model, before any detailed API. If you want a quick tour of the syntax first, Jetpack Compose basics in the Kotlin track covers it. Here we go further into why Compose is built this way and what that means for how you write code. Compose needs the Android SDK (or Compose Multiplatform tooling) to run, so the Compose code is read-only, and the TryIt blocks are plain Kotlin stand-ins that model the ideas: a tree built from function calls, and a comparison between imperative and declarative updates. They are not the real Compose runtime, which is far more sophisticated.

Imperative views and their problem

In the View system, you describe a layout in XML and then manipulate the objects in code:

Kotlin
// read-only example: the View system
val title = findViewById<TextView>(R.id.title)
val error = findViewById<TextView>(R.id.error)
val button = findViewById<Button>(R.id.submit)

fun onSubmitFailed(message: String) {
    error.text = message
    error.visibility = View.VISIBLE
    button.isEnabled = true
}

fun onSubmitSucceeded() {
    // did we remember to hide the error? and re-enable the button?
    title.text = "Welcome back"
}

The UI is long-lived objects with mutable state, and every event handler must update the right combination of them. As screens grow, the number of combinations explodes and bugs creep in: a stale error message, a button that stays disabled, two views that disagree. The data (what is true) and the display (what the user sees) are two copies that you must keep in sync by hand.

The declarative idea

In Compose, there is one source of truth, the state, and the UI is a function of it:

Text
UI = f(state)

You do not tell the framework "hide the error". You write what the screen is for the current state, and the error simply is not part of the description when there is none:

Kotlin
// read-only example: Compose
@Composable
fun LoginForm(state: LoginState, onSubmit: () -> Unit) {
    Column {
        Text(if (state.loggedIn) "Welcome back" else "Please sign in")
        if (state.error != null) {
            Text(state.error, color = Color.Red)
        }
        Button(onClick = onSubmit, enabled = !state.loading) {
            Text("Sign in")
        }
    }
}

There is nothing to forget. The error text exists exactly when state.error is not null, and the button is enabled exactly when loading is false. When the state changes, Compose calls LoginForm again with the new state. This is called recomposition, and it is the same model that React, SwiftUI and Flutter use.

This does not mean the screen is rebuilt from scratch every time. Compose remembers what it drew and applies only the differences, and it skips functions whose inputs have not changed. You think in whole screens; the runtime works in small updates.

flowchart LR
    A["State"] -->|"read by"| B["Composable functions"]
    B -->|"describe"| C["UI tree"]
    C -->|"drawn as"| D["Screen"]
    D -->|"user event"| E["Event handler"]
    E -->|"updates"| A

The loop of a Compose screen: state flows down to the UI, events flow up and change the state.

Why functions?

Compose builds UI from functions rather than classes with XML for a reason that goes beyond fashion. A function:

  • takes its inputs as parameters, so what a piece of UI depends on is visible in its signature;
  • can use any Kotlin feature: if, for, when, your own helper functions and data;
  • is composed by calling it from another function, so a large screen is simply small functions calling each other;
  • has no inheritance hierarchy to learn: there is no ButtonView extending TextView extending View.

Because a composable function is ordinary Kotlin, a list of rows is a for loop and a conditional section is an if. In XML you would need <include>, visibility toggling or adapters. The details of writing composables come in Composable Functions.

The composition tree

When Compose runs your composable functions, it records what they emit in a tree called the composition. Column contains its children, a Button contains its Text. The tree is what Compose measures, positions and draws.

flowchart TD
    A["ProfileCard"] --> B["Column"]
    B --> C["Text 'Ada Lovelace'"]
    B --> D["Row"]
    D --> E["Icon"]
    D --> F["Text 'Mathematician'"]

A composable that calls composables produces a tree of nodes.

Compose draws a frame in three phases, and knowing their names helps you read later lessons:

  1. Composition: run the composable functions to decide what to show (builds or updates the tree).
  2. Layout: measure and place every node in the tree (where).
  3. Drawing: paint the nodes on a canvas (how it looks).

A state change triggers composition only if a composable read that state in its body; if only layout or drawing needs it, Compose can skip earlier phases. That is why Compose can be efficient even though your code looks like "redo everything".

The stand-in below makes the "functions build a tree" idea concrete. Small functions add nodes through a builder, and a render function prints the tree with indentation. The real Compose compiler plugin does the equivalent by adding a hidden parameter to each @Composable function so the runtime can track the call position.

Kotlin Functions that emit a tree (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The for loop produced two Row nodes and the if added a message only for the empty card. No XML, no adapter: ordinary code decides the shape of the tree.

Imperative bug versus declarative description

The second stand-in plays the login example from above both ways. The imperative version has "views" that event handlers update, and the success handler forgets to clear the error. The declarative version has one render function from state to lines of text, which cannot get out of sync because it recomputes everything from the state.

Kotlin Imperative updates versus a function of state (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

In the imperative run, the final line still shows the old error next to "Welcome back". In the declarative run, there is no way to forget: the error disappeared because the new state has none.

Rules that follow from the model

Because Compose may run your function often, in any order, and may skip it, a composable function should behave like a pure description:

  • No side effects in the body. Do not write to a file, start a network call or change a global variable while composing. Side effects get their own tools (Side Effects).
  • Read state, do not hide it. Anything that changes what is shown must be state that Compose can observe (State and remember).
  • Do not assume order or count. A composable may be called again at any time, or not at all, when its inputs did not change.
  • Keep data flowing down and events flowing up. Pass values as parameters and report user actions through lambdas. This pattern, called state hoisting, makes composables easy to test and to preview.

Starting Compose and previews

Compose enters your app through setContent, which you saw in Activities and setContent. Everything under it is composable functions:

Kotlin
// read-only example
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MaterialTheme {
                LoginRoute()
            }
        }
    }
}

Because a composable is just a function of its parameters, you can ask Android Studio to draw it without running the app. Annotate a function with @Preview and Studio shows it in a side panel:

Kotlin
// read-only example
@Preview(showBackground = true)
@Composable
private fun LoginFormPreview() {
    MaterialTheme {
        LoginForm(
            state = LoginState(error = "Wrong password"),
            onSubmit = {},
        )
    }
}

Previews are one of the best payoffs of the declarative model. To see the error state you do not have to reproduce a failed login: you pass a state that has an error. A preview for each state (loading, empty, error, content) is a fast visual test. Previews do not run on a real device, so anything that needs the network, a database or a ViewModel must be passed in as plain parameters; this is another reason to keep composables simple. You will build on this in Composable Functions.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the core idea of declarative UI in Compose?

    UI = f(state). You write what the screen looks like for a state; Compose reruns the affected functions when the state changes.
  2. 2. Why is a stale error message unlikely in a Compose screen?

    The conditional in the composable ties the error to the state. When the state no longer has an error, the new description has no error node.
  3. 3. What are the three phases Compose goes through to draw a frame?

    Compose decides what to show (composition), measures and places nodes (layout) and paints them (drawing). A state read in a later phase can skip earlier ones.
  4. 4. Why should a composable function avoid side effects in its body?

    A composable can be recomposed many times or skipped. Work with side effects must go through the effect APIs that control when it runs.
  5. 5. What does the @Preview annotation let you do?

    Because a composable depends only on its parameters, Studio can render it from sample data. This makes it easy to preview every state of a screen.

Summary

  • Compose is declarative: you describe the UI as a function of state and Compose updates the screen when the state changes.
  • Imperative views duplicate truth (data and widgets); Compose has one source of truth, so stale-UI bugs are much rarer.
  • Composables are plain Kotlin functions, so if, for and helper functions shape the UI.
  • Running composables builds the composition tree, which Compose lays out and draws in separate phases.
  • Keep composables free of side effects, pass data down as parameters and send events up as lambdas.
  • setContent starts Compose in an activity; @Preview draws a composable from sample parameters without running the app.
  • The Compose code is read-only; the TryIts are stand-ins modeling trees and function-of-state updates.

Next: Composable Functions