Composables and modifiers

Learn how Jetpack Compose runs, re-runs or skips composable functions, and why modifier order changes what users see and what they can tap. About 22 minutes.

Why it matters

  • Modifier order is a frequent cause of 'it looks wrong but the code seems fine' bugs. A one-line swap of .padding() and .background() changes the rendered result.
  • Interviewers ask why a composable can be skipped and what that implies for side effects and work done in the body.
  • Stateless composables (state down, events up) keep screens easy to preview, test and reuse.
  • Every reusable composable should accept a modifier: Modifier = Modifier parameter and apply it to its root. Without it, callers cannot size, position or tag the component.

The simple explanation

  • A composable is like a recipe card: the kitchen may cook it twice, skip it, or cook it out of order. The card itself holds no state.
  • A modifier chain is like wrapping a gift: each layer (paper, ribbon, bow) is applied in sequence. Swap two layers and the look changes.
  • Padding before background means 'leave a gap, then paint what is left'. Padding after background means 'paint the whole box, then indent the content'.
  • A stateless composable takes ingredients (parameters) and describes a dish (UI). It does not keep a pantry of its own.

A composable is a Kotlin function annotated with @Composable that usually returns Unit and emits UI. The Compose runtime treats it as a description, not a one-time call. The runtime may recompose it (call it again), skip it (if its inputs did not change), or call composables in a different order. So the body must not contain side effects, and expensive work belongs in remember or the ViewModel.

A modifier is a value of type Modifier that you attach to a layout. Modifiers are chainable and order-sensitive: each call wraps the result of the calls before it. The chain is read left to right, outermost first.

ChainWhat happens
.background(gray).padding(16.dp)Gray fills the full size; text is indented inside the gray.
.padding(16.dp).background(gray)Space is reserved first; gray is painted only on the inner area.

The same rule applies to touch: .clickable { }.padding(16.dp) makes the padding part of the tap area, while .padding(16.dp).clickable { } does not. For size modifiers, the earlier one wins: Modifier.width(100.dp).width(200.dp) is 100 dp wide.

Every reusable composable should accept modifier: Modifier = Modifier as its first optional parameter and apply it first, on the root layout, so callers control size, position and behaviour from outside.

A stateless composable takes all data as parameters and emits UI. It holds no mutableStateOf of its own. State lives in the caller (or a ViewModel), and user actions go out through lambdas. This is the state down, events up rule.

Because the body can run again on every recomposition, anything you compute there is computed again each time. That is fine for cheap values. For expensive work (compiling a Regex, sorting a big list) use remember or move it out of the composable. This is the bridge to the State and remember lesson.

Notes

  • A composable is a @Composable function that emits UI. The runtime may call it many times, in any order, or skip it.
  • Modifier order is left-to-right, outermost-first. .padding().background() and .background().padding() look different. This is a common visual bug.
  • By convention, a reusable composable declares modifier: Modifier = Modifier as the first optional parameter and applies it to the root layout, once.
  • Stateless composables take data as parameters and emit UI. They hold no mutableStateOf. Data flows in, user actions flow out via lambda callbacks.
  • Work in the body repeats on every recomposition. Cheap values are fine. Wrap expensive ones in remember { } or compute them in the ViewModel.
  • Modifier is an interface, and its companion object Modifier is the empty starting point. You build a value by chaining: Modifier.fillMaxWidth().padding(8.dp).clickable { }.
  • A composable runs again when state it reads changes, or when its parent recomposes and passes different arguments. If the arguments are equal, Compose can skip it.
  • Do not log, start coroutines, or mutate outside objects in the body. Use LaunchedEffect, DisposableEffect or SideEffect (covered in a later lesson).
  • Clickable placement matters too: .clickable before .padding includes the padding in the touch target.

Code example

Two versions of the same card: one with padding outside the background, one with padding inside. Both take a modifier from the caller.

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
 
@Composable
fun GreetingCard(
    message: String,
    modifier: Modifier = Modifier,   // first optional parameter
    onClick: () -> Unit = {},
) {
    // padding OUTSIDE background: gray area is smaller, space around it
    Text(
        text = message,
        modifier = modifier
            .padding(16.dp)
            .background(Color.LightGray, shape = RoundedCornerShape(8.dp))
            .clickable(onClick = onClick),
        style = MaterialTheme.typography.bodyLarge,
    )
}
 
@Composable
fun GreetingCardFilled(
    message: String,
    modifier: Modifier = Modifier,
) {
    // padding INSIDE background: gray fills full size, text indented
    Text(
        text = message,
        modifier = modifier
            .background(Color.LightGray, shape = RoundedCornerShape(8.dp))
            .padding(16.dp),
        style = MaterialTheme.typography.bodyLarge,
    )
}
 
// Caller: passes a modifier from outside; the cards stay stateless
@Composable
fun Screen() {
    Column(
        modifier = Modifier.fillMaxSize().padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(12.dp),
    ) {
        GreetingCard(message = "Hello", modifier = Modifier.fillMaxWidth())
        GreetingCardFilled(message = "Hello", modifier = Modifier.fillMaxWidth())
    }
}
  • modifier comes after the required message and defaults to Modifier, so callers can leave it out. It starts the chain, so the caller's size and position apply before the card's own modifiers.
  • The two cards differ only by the order of .padding() and .background().
  • onClick is a lambda (event up). The card does not decide what a click does; the caller does. Because .clickable comes after .padding, only the gray area reacts to taps.

Run the idea in plain Kotlin

A tiny model of a modifier chain: each step works on the space left by the steps before it.

sealed class Mod
data class Padding(val dp: Int) : Mod()
data class Background(val color: String) : Mod()

fun describe(chain: List<Mod>, width: Int) {
  var available = width
  for (m in chain) {
      when (m) {
          is Padding -> {
              available -= 2 * m.dp
              println("  padding " + m.dp + ": content area is now " + available + " wide")
          }
          is Background -> println("  background " + m.color + ": paints " + available + " wide")
      }
  }
}

fun main() {
  println("background then padding:")
  describe(listOf(Background("gray"), Padding(16)), 200)
  println("padding then background:")
  describe(listOf(Padding(16), Background("gray")), 200)
}

Expected output:

background then padding:
  background gray: paints 200 wide
  padding 16: content area is now 168 wide
padding then background:
  padding 16: content area is now 168 wide
  background gray: paints 168 wide

In production

Cards that suddenly touched each other
  • After a theming refactor, product cards in a list lost the gap between them. Their gray backgrounds ran into each other and into the screen edge.
  • A developer had moved .padding(16.dp) from before .background() to after it.
  • The padding still existed, but it was now inside the painted area, so it only indented the text.
The fix
  • Restored the order: .padding(16.dp) (outer gap) first, then .background(), then an inner .padding() for the text if needed.
  • Added screenshot tests (for example with Paparazzi or Roborazzi) for the card so a visual change shows up in review.
  • Added a review habit: when a modifier chain changes, read it top to bottom as 'outer to inner'.
A card that ignored the caller's modifier
  • A UI test could not find a card by its Modifier.testTag("product_card"), and fillMaxWidth() from the screen had no effect.
  • The card did declare modifier: Modifier = Modifier, but the body never used it. It started its own chain with Modifier.padding(8.dp).
  • On another screen the opposite bug appeared: the modifier was applied to both the root and an inner Text, so padding showed up twice.
The fix
  • Applied modifier exactly once, at the start of the root layout's chain: Column(modifier.padding(8.dp)).
  • Children of the card use a fresh Modifier, never the parameter.
  • Added a static check: Slack's open-source compose-lints rules flag a modifier parameter that is reused on several children or not applied to the root.

Common mistakes

  • Swapping .padding() and .background() by accident. Padding before background leaves a gap outside the painted area; padding after background indents the content inside it. Read the chain as outer to inner.
  • Omitting the modifier parameter on a reusable composable. Callers cannot size, position or tag it, so layouts and UI tests get harder. Declare modifier: Modifier = Modifier and apply it to the root.
  • Applying internal size modifiers before the caller's modifier. The earlier size modifier wins, so Modifier.fillMaxWidth().then(modifier) ignores a caller's width(120.dp). Start the chain with modifier.
  • Doing expensive work in the body without remember. Compiling a Regex or sorting a large list repeats on every recomposition. Use remember (with keys if the input changes) or do it in the ViewModel. Cheap values do not need remember.
  • Holding mutableStateOf inside a component that the parent needs to control. The parent cannot read or reset the value, and previews and tests must click through it. Pass the value in and send events out.
  • Logging or starting a coroutine directly in the body. The body may run many times or be skipped, so the side effect fires unpredictably. Use LaunchedEffect for work tied to keys, or SideEffect for syncing state to non-Compose code after each successful recomposition.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“What is a composable and how is it different from a regular Kotlin function?”

“Why does modifier order matter? Give a concrete example.”

“What does it mean that a composable can be skipped?”

“How do you design a stateless composable?”

Quiz

What happens if you swap .padding(16.dp) and .background(Color.Gray) so background comes first?

Where does the modifier parameter go in a reusable composable?

A parent recomposes and passes exactly the same arguments to a child composable. What usually happens to the child?

Which of these is worth wrapping in remember (or moving out of the composable)?

0 of 4 answered

Mini task

Exercise: Fix the modifier order and add the missing parameter (15 min)

  1. Create a composable UserBadge(name: String) that shows a Text with a circular background and 12 dp padding. Do not add a modifier parameter yet.

  2. Put it inside a Box in a parent screen. Notice that you cannot size or position the badge from the parent. This is the bug.

  3. Add modifier: Modifier = Modifier after name. Apply it first in the chain, before .background() and .padding().

  4. In the parent Box, call UserBadge(name = "Ada", modifier = Modifier.align(Alignment.TopEnd).size(48.dp)). Confirm the badge moves to the top-right corner and is 48 dp.

  5. Swap .padding(12.dp) and .background(Color.Blue, CircleShape). Observe the difference. Swap back. Write a one-line comment above each order explaining what it does.

  6. Add LaunchedEffect(Unit) { Log.d("Badge", "Badge entered composition") } inside the composable. Change the name argument from the parent with a button. Confirm the log appears once, not on every recomposition. (This previews the side-effects lesson.)

Done condition: The badge is positioned by the caller, the modifier order is commented, and the LaunchedEffect log appears once.

Next: Layouts: Row, Column, Box