In Jetpack Compose, a profile header passes scrollState.value into Modifier.offset(y = ...) and recomposes every scroll frame; how do lambda modifiers fix it?
answer
- three phases, each tracked separately
- where the read happens decides the cost
- placement step, not composition
- graphicsLayer block versus its parameters
basics
~20 sCompose reruns work from the phase that read a state. Reading the scroll inside Modifier.offset { } defers it to placement, and graphicsLayer { } or drawBehind { } defer alpha or colour, so scrolling stops recomposing.
solid answer
~40 sCompose has three phases (composition, layout, drawing) and records which phase read each snapshot state. `Modifier.offset(y = ...)` takes a value, so `scrollState.value` is read in composition and every scroll frame recomposes, re-measures and redraws the content although only a position changed. The lambda overload `Modifier.offset { IntOffset(0, -scrollState.value / 2) }` runs in the placement step, so a change re-runs placement and drawing only. For fade and scale, read the state inside `Modifier.graphicsLayer { alpha = ... }`, which updates layer properties without recomposition or relayout; for a colour, `drawBehind { }` re-runs only drawing. Reads that change what is shown stay in composition.
code
kotlin · 23 lines@Composable
fun CollapsingProfile(avatar: Painter) {
val scrollState = rememberScrollState()
Box {
Column(Modifier.verticalScroll(scrollState)) {
Spacer(Modifier.height(160.dp))
// profile sections
}
Image(
painter = avatar,
contentDescription = "Profile photo",
modifier = Modifier
.size(96.dp)
.offset { IntOffset(x = 0, y = -scrollState.value / 2) }
.graphicsLayer {
val progress = (scrollState.value / 300f).coerceIn(0f, 1f)
alpha = 1f - progress
scaleX = 1f - 0.4f * progress
scaleY = scaleX
},
)
}
}go deeper
Recall the three phases in order, composition, layout and drawing, and that Modifier.offset has a value form and a lambda form.
Explain that Compose records which phase read a state and restarts from there, and map offset lambdas to placement, graphicsLayer blocks to layer properties and drawBehind to drawing.
Diagnose a per-frame recomposition from the code alone, move each read to the right phase, keep the reads that change the tree in composition, and avoid the onSizeChanged-to-padding loop.
Decide where deferral is worth enforcing, for scroll- and animation-driven surfaces, and where plain value overloads stay the readable default, and back it with measured recomposition counts.
## Three phases, tracked separately Jetpack Compose builds each frame in three phases: 1. **Composition** runs composable functions and builds or updates the UI tree. 2. **Layout** measures each node and then places it. Measurement and placement have separate restart scopes, so a read in the placement step does not re-run measurement. 3. **Drawing** renders each node into the canvas. Compose records **which phase read each snapshot state**. When the state changes, Compose restarts the work from that phase onward and skips the earlier ones. So for a value that changes every frame, *where* you read it decides the cost far more than *whether* you read it. | Where the state is read | Examples | What runs again when it changes | |---|---|---| | Composable body, or a value passed to a modifier | `Modifier.offset(y = ...)`, `Modifier.alpha(a)`, `Modifier.padding(p)` | composition, then layout and drawing | | Measure block | the measure lambda of `Layout`, a layout modifier's `measure` | layout, and drawing if size or position changed | | Placement block | the `Modifier.offset { }` lambda, the placement block of `layout(w, h) { }` | placement, then drawing | | Layer block | `Modifier.graphicsLayer { }` | the layer's properties only: no recomposition, no relayout | | Draw block | `Modifier.drawBehind { }`, `drawWithContent { }`, `Canvas` | drawing only | ## The collapsing profile header A profile screen scrolls a `Column` with `Modifier.verticalScroll(scrollState)` while the avatar drifts up and fades. The first version reads the scroll in the composable body: ```kotlin val y = with(LocalDensity.current) { (scrollState.value / 2).toDp() } Image(avatar, null, Modifier.offset(y = -y).alpha(1f - scrollState.value / 300f)) ``` `scrollState.value` changes on every scroll frame, and because it is read during composition the whole enclosing content recomposes, then measures, lays out and draws, although nothing on screen changed except a position and an opacity. The fix moves each read into the phase that actually uses it: 1. Position goes into the lambda overload, `Modifier.offset { IntOffset(0, -scrollState.value / 2) }`. The lambda runs in the placement step, so a change re-runs placement and drawing and no recomposition. 2. Opacity and scale go into `Modifier.graphicsLayer { alpha = ...; scaleX = ...; scaleY = ... }`. A state read inside that block updates only the layer's properties, without recomposition or relayout. The parameter overload, `graphicsLayer(alpha = a)`, reads its value in composition and gains nothing. 3. A colour that tracks the scroll goes into `Modifier.drawBehind { drawRect(color) }`, which re-runs drawing only. 4. Anything that changes **what** is shown, such as a compact title appearing once the header has collapsed, must still be read in composition. Turning the per-frame value into a rarely changing boolean is a job for `derivedStateOf`, covered with Compose state. ## What the lambda costs The lambda overloads are not free: a lambda is allocated and invoked where a plain value would be passed. For a value that changes every frame, such as a scroll offset or a running animation, that cost is far smaller than a recomposition per frame. For a value that changes once in a while, such as a padding toggled by a setting, the plain value overload is clearer and costs nothing measurable. Defer reads where the value moves continuously, not everywhere. ## The opposite trap: feeding layout back into composition A related bug runs in the other direction. A header measures the avatar with `Modifier.onSizeChanged { imageHeightPx = it.height }`, stores the result in state, and uses it as `Modifier.padding(top = ...)` on the name below: - Frame one composes with a height of 0, lays out, and `onSizeChanged` writes the real height. - That write schedules a recomposition for the next frame, but the current frame is drawn with zero padding, so the name overlaps the avatar. - Frame two composes with the right value and the content jumps into place. Each pass is legal, and the result is an extra frame and a visible jump. The fix is to let a layout do the work in one pass: a `Column` already places the name below the avatar, and a custom `Layout` or `Modifier.layout` can measure one child and place another relative to it in the same layout pass. ## A short checklist - Read per-frame values in the latest phase that needs them: placement for position, the layer block for alpha, scale, rotation and translation, the draw block for colours. - Keep composition reads for values that change the UI tree itself. - Do not route a measured size through state into a layout modifier; use a layout that knows both children. - Confirm the result with the recomposition counts Android Studio's Layout Inspector shows, rather than by guessing.
- Why does Modifier.graphicsLayer(alpha = animatedAlpha) still recompose on every frame while graphicsLayer { alpha = animatedAlpha } does not?The parameter overload receives a plain value, so the state behind `animatedAlpha` is read where the modifier is built, in composition, and every change recomposes. The block overload defers the read into the layer block, which Compose re-runs on its own when the state changes, updating only layer properties without recomposition or relayout.
- When is it still correct to read a scroll position during composition in Compose?When the value decides what the UI tree contains, not just where or how it is drawn: showing a compact title once the header is collapsed, swapping a button. Then reduce the per-frame value to the coarse fact the UI needs, such as a boolean, so composition re-runs only when that fact flips; that filtering belongs to Compose's state tools rather than to modifiers.
- Every state read costs the same, so where you read it does not matter.
- The lambda overload of offset is free, so use it for every value.
- graphicsLayer(alpha = a) and graphicsLayer { alpha = a } behave the same.
- Writing a measured size to state in onSizeChanged and using it as padding is fine.
- Reading state inside drawBehind triggers a full recomposition of the composable.