Skip to content
Tutorials Center
My learning

Topics

Lesson 118 of 134 ยท Testing and Tooling

Jetpack Compose Basics

Learn Jetpack Compose basics: composable functions, state and recomposition, state hoisting, modifiers and lists, with runnable stand-ins that model how declarative UI works.

For many years, Android screens were built from XML layout files and Java or Kotlin code that found each view and changed it by hand: textView.setText(...), button.setVisibility(...). The more state a screen had, the harder it was to keep the views and the data in agreement. Jetpack Compose replaces this with a different idea: you write a Kotlin function that describes what the screen looks like for the current data, and the framework updates the screen whenever the data changes.

This is called declarative UI, and it is also the model of React, SwiftUI and Flutter. Compose uses ordinary Kotlin features that you have already met: functions, lambdas, default and named arguments, trailing lambda syntax and delegated properties. Compose needs an Android device, an emulator or the Compose Multiplatform desktop tooling, so the Compose code below is read-only. To learn the idea itself, the TryIt blocks model a tiny declarative UI in plain Kotlin that does run here. For where Compose fits, see Kotlin on Android.

Composable functions

A composable function is a function annotated with @Composable. Instead of returning a value, it emits UI by calling other composables:

Kotlin
// read-only example: needs Android or Compose Multiplatform
@Composable
fun Greeting(name: String) {
    Text(text = "Hello, $name!")
}

@Composable
fun WelcomeScreen() {
    Column {
        Greeting("Ada")
        Greeting("Linus")
        Button(onClick = { println("clicked") }) {
            Text("Say hi")
        }
    }
}

Look at how it reads. Column takes a trailing lambda (its content), and Button takes onClick plus a trailing lambda for what is drawn inside. The functions are named with an uppercase first letter because they behave like UI "elements" rather than actions. A composable describes a piece of UI and has no return value; the data goes in as parameters, and events go out as lambda parameters such as onClick.

The runtime calls your composables to build a tree of UI nodes:

flowchart TD
    A["WelcomeScreen"] --> B["Column"]
    B --> C["Greeting('Ada')"]
    B --> D["Greeting('Linus')"]
    B --> E["Button"]
    C --> F["Text 'Hello, Ada!'"]
    D --> G["Text 'Hello, Linus!'"]
    E --> H["Text 'Say hi'"]

Composables call composables; the result is a tree of UI nodes that Compose draws.

A UI tree in plain Kotlin

To see why this is a Kotlin feature and not magic, build a miniature version. The functions below take a lambda with receiver (see DSL builders) and add nodes to a tree. A render function prints the tree as text:

Kotlin A tiny declarative UI (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.

Greeting is an extension function on UiScope, which is a simple way to model "a function that adds UI". The real Compose compiler plugin does something more advanced (it adds a hidden parameter to every composable so the runtime can track where each call happened), but from the outside the experience is the same: nested function calls with trailing lambdas describe a tree.

State and recomposition

A function that only depends on its parameters would draw the same thing forever. Real screens change, so Compose has state. When the value of a state object changes, Compose recomposes every composable that read it: it calls them again with the new data and updates only the parts of the tree that differ.

Kotlin
// read-only example
@Composable
fun Counter() {
    var count by remember { mutableIntStateOf(0) }

    Column {
        Text("You clicked $count times")
        Button(onClick = { count++ }) {
            Text("Click me")
        }
    }
}

Three pieces work together:

  • mutableIntStateOf(0) creates an observable state holder. Writing to it notifies Compose.
  • remember { ... } stores the object between recompositions. Without it, each recomposition would create a fresh state and the counter would reset to 0 every time.
  • by is the delegated property syntax, so you can use count instead of count.intValue.

The loop of every Compose screen is: state is read while composing; an event (a click) changes the state; Compose recomposes the affected functions.

stateDiagram-v2
    [*] --> Composition: first draw
    Composition --> Idle: UI shown
    Idle --> EventHandled: user event
    EventHandled --> Recomposition: state changed
    Recomposition --> Idle: UI updated

State change triggers recomposition; the UI is always a function of the state.

The model below shows this loop without any Android parts. The Store holds the state, and view is a pure function from state to a text description of the UI. When an event changes the state, you call view again.

Kotlin UI as 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.

The reset button appears only when it makes sense, and you never wrote code to add or remove it. You described the screen for each state, and the framework did the rest. That is the main productivity gain compared to updating views by hand.

State hoisting

If Counter keeps its own state, you cannot test it easily, and a parent cannot react to the number. The standard Compose pattern is state hoisting: move the state up to the caller and pass in two things, the current value and a lambda to request a change. The child becomes a stateless composable.

Kotlin
// read-only example
@Composable
fun CounterScreen() {
    var count by remember { mutableIntStateOf(0) }   // state lives here
    CounterView(count = count, onIncrement = { count++ })
}

@Composable
fun CounterView(count: Int, onIncrement: () -> Unit) {   // stateless, reusable, testable
    Button(onClick = onIncrement) {
        Text("Clicked $count times")
    }
}

"State flows down, events flow up" is the sentence to remember. In larger apps the state usually lives in a ViewModel, exposed as a StateFlow (see StateFlow and SharedFlow) and read in the UI with collectAsStateWithLifecycle().

Modifiers, layouts and lists

A modifier is an ordered chain of decorations: size, padding, background, click handlers. Every composable takes an optional modifier parameter, and the order of the calls matters:

Kotlin
// read-only example
@Composable
fun ProfileCard(name: String, onOpen: () -> Unit, modifier: Modifier = Modifier) {
    Row(
        modifier = modifier
            .fillMaxWidth()
            .clickable(onClick = onOpen)
            .padding(16.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Text(name, style = MaterialTheme.typography.titleMedium)
        Spacer(Modifier.weight(1f))
        Text("Open")
    }
}

Putting .padding(16.dp) before .clickable would make the padding part of the clickable area; after it, the padding sits inside. The main layouts are Column (vertical), Row (horizontal) and Box (stacked). For long lists use LazyColumn, which composes only the visible items, like a RecyclerView without the boilerplate:

Kotlin
// read-only example
@Composable
fun NameList(names: List<String>) {
    LazyColumn {
        items(names, key = { it }) { name ->
            ProfileCard(name = name, onOpen = { /* navigate */ })
        }
    }
}

A stable key lets Compose keep the identity of an item when the list is reordered. The modifier: Modifier = Modifier parameter with a default value is a named and default argument convention in every well-written composable.

Rules worth knowing

  • Composables can run often and in any order. Do not put side effects (network calls, writing files) directly in the body. Use effect APIs such as LaunchedEffect, which runs a coroutine tied to the composable's life.
  • Use immutable data (data classes with val, List that you do not mutate). Compose skips recomposition for unchanged, stable parameters. Mutating a list in place does not notify Compose.
  • Keep state as low as possible and hoist it only as far as needed.
  • Compose Multiplatform from JetBrains runs the same code on Android, iOS, desktop and web (see Multiplatform).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a @Composable function do?

    A composable emits UI by calling other composables. Compose can call it again whenever the state it reads changes.
  2. 2. Why is remember { mutableIntStateOf(0) } used inside a composable?

    A composable can run many times. remember stores the object across those runs; without it the state would reset to its start value each time.
  3. 3. What does state hoisting mean?

    The child becomes stateless: it receives the current value and a callback. State flows down and events flow up.
  4. 4. Why does modifier order matter, for example padding before or after clickable?

    A modifier chain is applied step by step. Padding before clickable makes the padding part of the clickable area; after it, the padding is inside.

Summary

  • Compose describes the UI as a function of state: @Composable functions emit UI by calling other composables.
  • Trailing lambdas and lambdas with receivers are what make the syntax look like a layout language.
  • remember plus mutableStateOf keeps state; changing it triggers recomposition of the code that read it.
  • Hoist state: pass the value down and events up, so composables are stateless and testable.
  • Modifiers are an ordered chain of decorations; LazyColumn handles long lists.
  • Avoid side effects in composable bodies and prefer immutable data.
  • Compose code needs Android or Compose Multiplatform tooling, so it is read-only in the runner; the stand-ins model the same ideas.

Next: Kotlin Performance and Bytecode