DEV Community

Cover image for Where You Read Matters: Steering Compose Work with Deferred State Reads, derivedStateOf, and remember Keys
Android Expert
Android Expert

Posted on Originally published at Medium

Where You Read Matters: Steering Compose Work with Deferred State Reads, derivedStateOf, and remember Keys

Most Compose performance advice asks “will this recompose?” A better question is “which phase reads this state, and which phases do I actually want to pay for?”

Picture a podcast app. The episode list has a cover image that fades and drifts as you scroll, a thin reading-progress bar, and a “jump to latest” button that appears once you are a few items down. All three react to scroll position. All three can be written so that every scrolled pixel recomposes half the screen, or so that composition barely runs at all.

The difference is rarely about stability annotations or clever caching. It is about where in the frame you read the state. This post builds that mental model, shows the Kotlin that exploits it, and walks through the failure modes that bite teams in production.

What you will take away

  • Compose runs three phases per frame, and each phase tracks its own state reads.
  • Moving a read from the composable body into a layout or draw lambda can remove recomposition entirely.
  • derivedStateOf is for reducing the rate of change, not for "making state cheaper."
  • remember keys and derivedStateOf solve different problems, and mixing them up causes stale-capture bugs.
  • Layout Inspector’s recomposition counts only tell part of the story. Know what they cannot see.

1. The three phases: composition, layout, drawing

Every frame, Compose moves through three phases in order:

  1. Composition runs your @Composable functions and decides what to show. The output is a tree of layout nodes.
  2. Layout has two steps: measure (how big is each node?) and place (where does it go?). It decides where things are and how big they are.
  3. Drawing issues draw commands for each node. It decides how things look.

three-phases

The ordering matters because the phases are not equally expensive. Composition executes your code, allocates, diffs and may touch the node tree. Layout re-measures or re-places nodes. Drawing replays or re-records draw instructions. When a state change can be absorbed by the last phase, the first two are skipped.

Compose does not decide this by guessing. It decides it by observing reads.

2. State read location determines which phase re-runs

Compose state objects (mutableStateOf, LazyListState, Animatable, animateFloatAsState's returned State, and so on) are tracked by the snapshot system. Whenever code reads a state value while a phase is executing, the runtime records "this scope depends on that state." When the value is written, only the scopes that recorded a read are invalidated.

The key detail is that composition, measure, placement and draw each record reads separately:

  • A read in a composable body invalidates the enclosing recompose scope, which then re-runs composition, then layout, then drawing for the affected nodes.
  • A read inside a layout or placement lambda invalidates layout only, then drawing.
  • A read inside a draw or graphics-layer lambda invalidates drawing only.

read-location-phases

Here is the same scroll-driven effect written the expensive way:

@Composable
fun EpisodeCover(listState: LazyListState, cover: Painter) {
    // Read happens in composition: this function recomposes on every scroll pixel.
    val scrollPx = listState.firstVisibleItemScrollOffset
    val scrollDp = with(LocalDensity.current) { scrollPx.toDp() }

    Image(
        painter = cover,
        contentDescription = null,
        contentScale = ContentScale.Crop,
        modifier = Modifier
            .fillMaxWidth()
            .height(240.dp)
            .offset(y = scrollDp / 2)                         // Dp overload: value, not lambda
            .alpha(1f - (scrollPx / 600f).coerceIn(0f, 1f))   // Float overload: value, not lambda
    )
}
Enter fullscreen mode Exit fullscreen mode

Nothing here is wrong in the sense of correctness. It looks fine and it works. But firstVisibleItemScrollOffset changes on essentially every scrolled pixel, and the read sits in the composable body, so the whole function re-executes for every frame of the fling. Both modifiers also take plain values, which means new modifier instances are produced and compared on each pass.

Where does a read actually land?

One subtlety trips people up. The recompose scope is the nearest enclosing non-inline composable function. Column, Row and Box take inline content lambdas, so a state read inside Column { ... } is attributed to the function that contains the Column, not to the Column. That is why a harmless-looking read deep in a layout can recompose a huge parent.

Two more places reads hide:

  • Property delegates. val offset by listState.something reads on every access, and the by keyword makes it invisible. Where the line sits (body or lambda) is what counts.
  • Parameters. fun Header(scroll: Int) forces whoever calls it to read the state to get an Int. The read is now in the caller's scope. This is the next section's main fix.

3. Lambda-based modifiers that skip composition

Compose ships lambda overloads for exactly this problem. A lambda is executed later, in a later phase, so reads inside it are recorded there.

  • Modifier.offset { } records reads in placement (layout phase).
  • Modifier.layout { } records reads in measure, or in placement if the read sits inside the layout(w, h) { } block.
  • Modifier.drawBehind { }, drawWithContent { } and Canvas { } record reads in draw.
  • Modifier.graphicsLayer { } records reads in the layer update, which is the draw side of the frame.

Rewriting the cover with a layer lambda:

@Composable
fun EpisodeCover(listState: LazyListState, cover: Painter) {
    Image(
        painter = cover,
        contentDescription = null,
        contentScale = ContentScale.Crop,
        modifier = Modifier
            .fillMaxWidth()
            .height(240.dp)
            .graphicsLayer {
                // Assumes this header is item 0 of the LazyColumn.
                val scroll = listState.firstVisibleItemScrollOffset
                translationY = scroll * 0.5f                          // half-speed parallax
                alpha = 1f - (scroll / size.height).coerceIn(0f, 1f)  // fade out
            }
    )
}
Enter fullscreen mode Exit fullscreen mode

The composable body no longer reads any scroll state. Composition runs once. Each scroll frame only updates layer properties, and changing a layer’s translation or alpha does not even force the node’s content to be re-recorded. This is the cheapest path Compose offers.

Pass lambdas, not values, down the tree

The same principle works across function boundaries. A child that takes progress: Float makes its parent do the read. A child that takes progress: () -> Float lets the child read it where it chooses:

@Composable
fun ReadingProgressBar(progress: () -> Float, modifier: Modifier = Modifier) {
    val track = MaterialTheme.colorScheme.surfaceVariant
    val bar = MaterialTheme.colorScheme.primary

    Box(
        modifier
            .fillMaxWidth()
            .height(4.dp)
            .drawBehind {
                drawRect(track)
                drawRect(
                    color = bar,
                    size = size.copy(width = size.width * progress().coerceIn(0f, 1f))
                )
            }
    )
}

// Call site: the read happens inside drawBehind, not here.
ReadingProgressBar(progress = {
    val max = scrollState.maxValue
    if (max == 0) 0f else scrollState.value / max.toFloat()
})
Enter fullscreen mode Exit fullscreen mode

Note the guard for maxValue == 0. A divide that yields NaN slips straight past coerceIn, because NaN fails every comparison, and you get an invisible or broken bar.

Material 3 follows the same pattern in its own APIs. The progress indicators accept a progress: () -> Float overload for precisely this reason, so use the lambda versions when the value animates.

If you are worried about allocating a new lambda on each recomposition: strong skipping mode, which is on by default from Kotlin 2.0.20 with the Compose compiler Gradle plugin, remembers every lambda inside a composable, keyed on its captures. Stable captures are compared with equals and unstable ones with instance equality, so a lambda like { listState.firstVisibleItemScrollOffset } is reused across recompositions. On older toolchains, enable it explicitly and confirm it is on for your build rather than assuming.

Offset-driven gestures

Drag interactions are the classic case for offset { }:

import kotlin.math.abs
import kotlin.math.roundToInt

@Composable
fun DismissibleRow(
    onDismissed: () -> Unit,
    modifier: Modifier = Modifier,
    content: @Composable RowScope.() -> Unit,
) {
    var dragX by remember { mutableFloatStateOf(0f) }
    val thresholdPx = with(LocalDensity.current) { 120.dp.toPx() }

    Row(
        modifier = modifier
            // Gesture first, offset second, so the touch target does not move with the content.
            .draggable(
                orientation = Orientation.Horizontal,
                state = rememberDraggableState { delta -> dragX += delta },
                onDragStopped = {
                    if (abs(dragX) > thresholdPx) onDismissed() else dragX = 0f
                },
            )
            .offset { IntOffset(dragX.roundToInt(), 0) },
        content = content,
    )
}
Enter fullscreen mode Exit fullscreen mode

dragX is read inside the offset lambda (the by delegate fires there), so dragging re-runs placement only. Modifier order also matters. With .offset placed before .draggable, the pointer-input node sits inside the offset and moves with the content, so its local coordinates shift while the finger is still moving. That is a commonly reported cause of jitter, though how visible it is depends on your gesture setup, so test it on a device before settling on an order.

Pitfalls specific to deferring reads

  • Capturing the value outside the lambda defeats the whole thing. val x = state.value above graphicsLayer { translationX = x } is a composition read again. The read must be inside the lambda.
  • Layout-phase reads that change size cascade. Reading state in the measure part of Modifier.layout { } and returning a different size forces a re-measure of that subtree and its parents' placement. Reading in the placement block is far cheaper.
  • Alpha on a layer can allocate an offscreen buffer. With the default compositing strategy, graphicsLayer { alpha = ... } below 1 may render the node into an offscreen buffer so overlapping children fade as one unit. If your content does not overlap itself, compositingStrategy = CompositingStrategy.ModulateAlpha avoids that cost.
  • Do not put graphicsLayer on everything. Each layer has overhead. Use it where the property actually changes frequently.

4. derivedStateOf for thresholds

Not every scroll-driven UI can be deferred into a draw lambda. Showing or hiding a button changes what is in the tree, so it has to happen in composition. That is exactly where derivedStateOf earns its place.

The “jump to latest” button should appear once the user is past item 2:

@Composable
fun EpisodeList(episodes: List<Episode>, modifier: Modifier = Modifier) {
    val listState = rememberLazyListState()
    val scope = rememberCoroutineScope()

    val showJumpToLatest by remember {
        derivedStateOf { listState.firstVisibleItemIndex > 2 }
    }

    Box(modifier) {
        LazyColumn(state = listState) {
            items(episodes, key = { it.id }) { episode -> EpisodeRow(episode) }
        }

        AnimatedVisibility(
            visible = showJumpToLatest,
            modifier = Modifier.align(Alignment.BottomEnd),
        ) {
            // Text-only button, so the snippet needs no icon artifact.
            ExtendedFloatingActionButton(
                onClick = { scope.launch { listState.animateScrollToItem(0) } },
            ) {
                Text("Jump to latest")
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

firstVisibleItemIndex changes every time a new item becomes the first visible one, which happens many times over a long scroll. Reading it directly in composition means EpisodeList recomposes at every item boundary even though the answer to "is it greater than 2?" stays true for dozens of items. derivedStateOf sits between the raw state and the reader: it re-evaluates its lambda when the input changes, but only notifies readers when the result changes.

derivedstateof-filtering

remember keys and what derivedStateOf can see

Two facts you must hold together:

  1. derivedStateOf tracks State reads inside its lambda automatically.
  2. It does not track plain Kotlin values captured by the lambda.

That second point is how stale-capture bugs happen:

@Composable
fun JumpButtonHost(listState: LazyListState, threshold: Int) {
    // BUG: `threshold` is captured on the first composition and never refreshed.
    val show by remember {
        derivedStateOf { listState.firstVisibleItemIndex > threshold }
    }
    // ...
}
Enter fullscreen mode Exit fullscreen mode

If a caller changes threshold (say, from a remote config or a tablet layout), nothing invalidates the remembered derived state. There are two clean fixes, and they solve it differently:

// Fix A: key remember so the derived state is rebuilt when the input changes.
val show by remember(listState, threshold) {
    derivedStateOf { listState.firstVisibleItemIndex > threshold }
}

// Fix B: turn the plain value into State so the lambda observes it.
val currentThreshold by rememberUpdatedState(threshold)
val show by remember(listState) {
    derivedStateOf { listState.firstVisibleItemIndex > currentThreshold }
}
Enter fullscreen mode Exit fullscreen mode

Fix A throws away and recreates the derived state when a key changes, which is simple and fine when keys change rarely. Fix B keeps one derived-state instance alive and lets it re-evaluate, which suits values that change often.

A quick mental model for the three tools:

  • remember(keys) answers "when should I recompute this value?" It compares keys with equals and runs only during composition.
  • derivedStateOf answers "how do I turn fast-changing State into slow-changing State?" It reacts to State writes, outside the recomposition cycle.
  • A deferred read answers “can I avoid composition entirely?” It moves the read into layout or draw.

A related trap is using remember keys to fake what derivedStateOf does:

// Looks clever, does nothing useful: using the offset as a key means you READ it in composition.
val show = remember(listState.firstVisibleItemScrollOffset) {
    listState.firstVisibleItemScrollOffset > 200
}
Enter fullscreen mode Exit fullscreen mode

Passing the offset as a key forces the read into composition, so you recompose on every change anyway.

If you only need a side effect at the threshold (an analytics event, say) and not a UI change, skip derived state and use snapshotFlow { listState.firstVisibleItemIndex > 2 }.distinctUntilChanged() inside a LaunchedEffect. No recomposition required at all.

5. Common mistake: derivedStateOf where it isn't needed

derivedStateOf is not free. It allocates a state object, registers observers, and re-runs your lambda after its dependencies change and something reads or observes the result. It pays off only when the output changes much less often than the input. Three recurring misuses:

1. The output changes exactly as often as the input.

// Wasteful: label changes whenever `selected` changes, so nothing is filtered.
val label by remember { derivedStateOf { "Episode ${selected + 1}" } }

// Just compute it.
val label = "Episode ${selected + 1}"
Enter fullscreen mode Exit fullscreen mode

2. The dependency is not State.

@Composable
fun Header(episodes: List<Episode>) {
    // BUG: `episodes` is a plain parameter. The lambda will not re-run when it changes.
    val hasMany by remember { derivedStateOf { episodes.size > 20 } }
}

// Correct and cheaper:
val hasMany = episodes.size > 20
Enter fullscreen mode Exit fullscreen mode

3. Using it to avoid a deferral that was available.

// Continuous value, read in composition: still recomposes every frame.
val fade by remember {
    derivedStateOf { 1f - listState.firstVisibleItemScrollOffset / 600f }
}
Modifier.alpha(fade)
Enter fullscreen mode Exit fullscreen mode

A continuous value like a fade has as many distinct outputs as inputs, so derivedStateOf filters nothing. The fix is the graphicsLayer lambda from section 3.

Other ways teams get burned:

  • Forgetting remember. derivedStateOf without remember creates a fresh object on each recomposition and loses all caching.
  • Heavy work inside the lambda. It re-runs after its dependencies change, whenever something reads or observes the derived state, and that usually happens on the main thread. A large filter over thousands of rows belongs in a ViewModel or behind snapshotFlow.
  • Side effects inside the lambda. It must be a pure function of State. Writing state from inside it invites loops and surprising ordering.
  • Expecting equality to save you from the work. Equal results do not invalidate readers, but the lambda itself still has to re-run after each dependency change to find out whether the result is equal.

do-you-need-derivedstateof

Use the flow in that diagram top to bottom. The order is deliberate: defer first, derive second, compute directly otherwise.

6. Measuring the difference with Layout Inspector’s recomposition counts

Reasoning is cheap, but a claim about performance should be measured. Layout Inspector in Android Studio can show, per composable, how many times it recomposed and how many times it was skipped.

A repeatable procedure

  1. Run a debuggable build on a device or emulator and attach Layout Inspector to the process.
  2. Enable the recomposition count columns in the Compose component tree through the inspector’s options (menu names shift between Android Studio versions, so look for the recomposition and skip counters).
  3. Reset the counts so you start from zero.
  4. Drive a deterministic gesture instead of scrolling by hand, for example adb shell input swipe 540 1600 540 400 150.
  5. Read the counts for the composables involved, then repeat on the alternate implementation.

recomposition-counts

The numbers above are illustrative of the pattern you should expect, not results from a specific device. Expect your own to vary with list length, fling velocity and device.

The shape is the lesson: a continuous value read in the body recomposes constantly, a deferred read can reach zero, and a threshold read lands in the single digits once derived.

A cheap in-code probe

When you cannot attach the inspector (CI, a user’s device, a quick debug build), a counter composable gives you the same signal in Logcat:

@Composable
fun RecompositionLogger(tag: String) {
    val count = remember { intArrayOf(0) }
    SideEffect {
        count[0]++
        Log.d("Recomp", "$tag recomposed ${count[0]}x")
    }
}
Enter fullscreen mode Exit fullscreen mode

Drop it inside the composable you suspect and delete it afterwards. It counts how many times the function completed a composition.

What the counts cannot tell you

This is the part most write-ups skip. Recomposition counts measure the composition phase only. After you move a read into graphicsLayer, the count falls to zero, but the work did not vanish. It moved to the draw phase, which is much cheaper and still not free. A zero in the inspector proves composition stopped; it does not prove the frame is fast.

To close the loop, measure frame cost:

  • Run a Macrobenchmark with FrameTimingMetric on a release-like build type (minified, not debuggable). It reports frame duration and overrun distributions, which is what users perceive.
  • Open a Perfetto or system trace of the same gesture to see where the frame time actually goes.
@get:Rule val benchmarkRule = MacrobenchmarkRule()

@Test
fun flingEpisodeList() = benchmarkRule.measureRepeated(
    packageName = "com.example.pods",
    metrics = listOf(FrameTimingMetric()),
    iterations = 8,
    startupMode = StartupMode.WARM,
    setupBlock = { pressHome(); startActivityAndWait() },
) {
    val list = device.findObject(By.res("episode_list"))
    list.setGestureMargin(device.displayWidth / 5)
    repeat(3) { list.fling(Direction.DOWN); device.waitForIdle() }
}
Enter fullscreen mode Exit fullscreen mode

(By.res needs Modifier.testTag("episode_list") plus testTagsAsResourceId = true on a parent, so the tag is exposed to UI Automator.)

Use the two tools for different jobs: Layout Inspector on a debug build to find which composable is over-recomposing, and Macrobenchmark on a release-like build to confirm the user-visible result.

A failure-mode checklist you can paste into code review

  • A scroll, drag or animation value is read in a composable body. Move the read into graphicsLayer, offset { } or drawBehind.
  • A child takes a Float/Int/Color that changes per frame. Change the parameter to a lambda (() -> Float) or pass the State.
  • val x = state.value sits above a lambda modifier. The read must be inside the lambda.
  • derivedStateOf without remember, or with plain parameters captured. Add keys or use rememberUpdatedState.
  • derivedStateOf whose output changes as often as its input. Delete it.
  • remember(someFastChangingValue) used as a poor man's derived state. Replace with derivedStateOf.
  • .offset { } placed before gesture modifiers. Reorder so the touch target stays put.
  • Fading overlapping content with graphicsLayer { alpha }. Check the compositing strategy.
  • A threshold used only for a side effect. Use snapshotFlow instead of recomposing.
  • “Fixed” because the inspector shows zero recompositions. Confirm with frame timing as well.

🔚 Closing thought

State in Compose is a dependency graph, and where you read a value decides which part of the frame subscribes to it. Treat every per-frame read as a small architectural decision: can it be deferred to layout or draw? If it genuinely drives structure, can it be thinned out with derivedStateOf? If neither, compute it directly and move on.

Further reading

📱 Go Beyond Using AI — Learn How to Actually Build It Into Your Android Apps

If you’re building Android apps in 2026, “adding AI” can’t just mean bolting on a chatbot API — it means understanding on-device inference, model trade-offs, and production realities well enough to ship a feature users actually trust. I highly recommend “Mastering Android AI: App to Intelligence” It’s a practical, code-first journey through the entire Android AI stack — from ML Kit and LiteRT to Gemma, Gemini, and MediaPipe — covering everything from your first “hello inference” screen to thermal throttling, model drift monitoring, and full applied projects like an AI-powered camera app and a health companion, with hands-on Kotlin builds at every step.


Originally published on Medium.

Top comments (0)