Skip to content
Cover image for the post: Jetpack Compose recomposition: find and fix wasted work

Jetpack Compose recomposition: find and fix wasted work

Table of Contents
  1. Measure recomposition before changing code
  2. Where a state read lands
  3. Fix 1: read scroll state inside a lambda modifier
  4. Fix 2: use derivedStateOf when you only need a threshold
  5. Fix 3: give LazyColumn items a stable key
  6. Fix 4: pass parameters Compose can skip
  7. (Advanced) Compiler reports and the stability configuration file
  8. (Advanced) Count recompositions in a test
  9. Gotchas

A Jetpack Compose list that scrolls a little rough, plus a review comment saying “this recomposes too much”, is usually where this starts.

Open Layout Inspector with recomposition counts turned on, use the screen, and look for counts that keep rising on elements whose content did not change. Most fixes fall into 4 groups. Read fast-changing state late, use derivedStateOf for thresholds, give lazy items keys, and pass parameters Compose can compare. In the sample inbox below, a fading header recomposed 16 times during a short scroll, and 0 times after one state read moved into a graphicsLayer { } lambda.

TL;DR

  • Measure first. Layout Inspector shows a composition count and a skip count for every node.
  • A state read in a composable body re-runs composition. The same read inside Modifier.offset { }, graphicsLayer { } or drawBehind { } does not.
  • derivedStateOf (or computedStateOf on runtime 1.13+) turns 40 recompositions into 1 for a “scrolled past the top” flag.
  • Without key, inserting at the top of a LazyColumn recomposed 17 rows. With it, 1.

What you’ll learn

  • How to read recomposition counts, and when a count is worth fixing.
  • 4 fixes, each with counts from a real run.
  • Why the stability rules in the docs may not match your compiler version.

If you write Compose screens daily and just need to fix a janky one, read up to Fix 3. Fix 4 and the Advanced sections help when a composable is not skipped and you want to know why.

Measure recomposition before changing code

Layout Inspector counts how many times each composable node recomposed and how many times Compose skipped it. Run a debuggable build on API 29 or higher, open the Running Devices window and click Toggle Layout Inspector. If the Component Tree has no count columns, enable Show Recomposition Counts under View Options.

Press Reset just before one interaction, such as a single fling, and read the 2 columns. You are looking for a count that rises on something whose content did not change, like a header that only fades or a row that stays on screen.

Debug builds are slow, so judge the counts and not the smoothness. Real jank is measured with Macrobenchmark on a release build, which a later post covers. My rule of thumb is to optimise when you can see a problem, meaning jank on a release build or counts climbing on unchanged elements in lists and animations. A count of 2 instead of 1 on a static settings screen is not worth restructuring code for.

The sample is an inbox of 200 messages with a fading header and a “Top” button, built with Kotlin 2.4.21, AGP 9.5.2 and Compose BOM 2026.11.01 (runtime 1.13.0), minSdk 24 and targetSdk 37. All counts come from an emulator with a Pixel 8 profile on API 37.

Where a state read lands

A Compose frame runs 3 phases in order. Composition decides what to show, layout decides where, and drawing renders it. Compose records which phase read a state value, and when that value changes it restarts from that phase.

A state value changes. If it was read in a composable body or a value modifier such as alpha(x), composition, layout and drawing run again. If it was read in Modifier.offset { } or a layout { } block, only layout and drawing run. If it was read in drawBehind { } or Canvas { }, only drawing runs.

Scroll offsets and animation values change every frame, so a read in the composable body costs a recomposition per frame.

Fix 1: read scroll state inside a lambda modifier

The header fades out over the first 300 px of scrolling. This version computes the fade in the composable body.

Header.kt
fun headerFade(state: LazyListState): Float =
if (state.firstVisibleItemIndex > 0) 1f
else (state.firstVisibleItemScrollOffset / 300f).coerceIn(0f, 1f)
@Composable
fun FadingHeaderEager(listState: LazyListState) {
val fade = headerFade(listState) // read during composition
Box(Modifier.fillMaxWidth().height(96.dp).graphicsLayer(alpha = 1f - fade)) {
Text("Inbox")
}
}
Kotlin

The fixed version moves the same call into the lambda form of graphicsLayer, which runs after composition.

Header.kt
@Composable
fun FadingHeaderDeferred(listState: LazyListState) {
Box(
Modifier.fillMaxWidth().height(96.dp)
.graphicsLayer { alpha = 1f - headerFade(listState) } // read after composition
) {
Text("Inbox")
}
}
Kotlin

I scrolled the list 30 times by 10 px and counted how often each composable ran.

header deferred=false, 30 scroll steps of 10px -> {FadingHeaderEager=16, MessageRow=4}
header deferred=true, 30 scroll steps of 10px -> {MessageRow=4}

I expected 30, not 16. A row is 56 dp, or 147 px on this emulator. After about 15 steps the first message leaves the screen and headerFade() returns before reading the offset, so Compose stops recomposing the header. It tracks the reads that happened in the last run, not every read the code could make. The 4 MessageRow runs are new rows scrolling into view.

Modifier.offset { } does the same job for a header that moves, and drawBehind { } for colours.

Fix 2: use derivedStateOf when you only need a threshold

The “Top” button should appear once the first message has scrolled away. Reading firstVisibleItemIndex directly recomposes the screen every time a new message reaches the top. With derivedStateOf, Compose recomposes only when the boolean flips:

Inbox.kt
@Composable
fun InboxDerived(messages: List<Message>, listState: LazyListState = rememberLazyListState()) {
val showTop by remember { derivedStateOf { listState.firstVisibleItemIndex > 0 } }
Box(Modifier.fillMaxSize()) {
MessageList(messages, listState, useKeys = true)
if (showTop) {
ScrollToTopButton(onClick = {})
}
}
}
Kotlin

These are the counts after 40 scroll steps of 150 px.

scrollToTop eager, firstIndex=40 -> {InboxEager=40, MessageRow=42, ScrollToTopButton=1}
scrollToTop derived, firstIndex=40 -> {InboxDerived=1, MessageRow=42, ScrollToTopButton=1}
scrollToTop computed, firstIndex=40 -> {InboxComputed=1, MessageRow=41, ScrollToTopButton=1}

The third line uses computedStateOf, which the Android docs now recommend for cheap checks like this on Compose runtime 1.13 and newer. It re-evaluates on every read instead of caching. Keep derivedStateOf for older versions or for expensive calculations read several times.

Skip both when the output changes as often as the input. derivedStateOf { offset / 2 } changes on every pixel anyway, so it only adds bookkeeping.

Fix 3: give LazyColumn items a stable key

Without a key, LazyColumn identifies items by position. Insert a message at index 0 and every position now holds a different message, so every composed row gets new parameters:

Inbox.kt
items(messages, key = { it.id }, contentType = { "message" }) { MessageRow(it) }
Kotlin
insert at top useKeys=false, firstIndex=0 -> {MessageList=1, MessageRow=17}
insert at top useKeys=true, firstIndex=1 -> {MessageList=1, MessageRow=1}

Watch firstIndex as well as the counts. With keys the list stays anchored on the message that was on top before, so the new one lands just above the viewport. In an inbox or chat, call listState.scrollToItem(0) after the insert if the user was already at the top.

The key must be unique and storable in a Bundle, such as an ID, and never the list index. contentType matters in lists that mix row types, because Compose reuses compositions only between rows of the same type.

Fix 4: pass parameters Compose can skip

When a parent recomposes, Compose compares each child’s parameters with the previous call and skips the child if nothing changed. Strong skipping has been the default since Kotlin 2.0.20, so every restartable composable can be skipped and lambdas inside composables are remembered for you. The docs say stable parameters are compared with equals() and unstable ones by instance (===).

This toolbar recomposes every second for its “Synced” label and passes a filtered list down.

Inbox.kt
@Composable
fun ToolbarFilterInComposition(all: List<Message>, tick: Int) {
Column {
Text("Synced $tick s ago")
UnreadCount(all.filter { it.unread }) // new list instance on every recomposition
}
}
Kotlin

filter returns a new list each time, so UnreadCount should run on every tick. Here are 10 ticks on 2 compiler versions.

# Kotlin 2.2.20
toolbar filterInComposition -> {ToolbarFilterInComposition=10, UnreadCount=10}
# Kotlin 2.4.21
toolbar filterInComposition -> {ToolbarFilterInComposition=10}

On 2.4.21 UnreadCount never ran. Kotlin 2.3.20 reports unstable messages: List<Message>, while 2.4.0 and 2.4.21 print the parameter with no stability label and the generated call compares it with equals(). The Kotlin 2.4 release notes say the final stability value does not change, and I have not found this documented. Treat it as what this version does today and check your own report.

Some things behaved the same on both versions. A data class with a var, or an ArrayList parameter, was compared by instance and recomposed on every tick. A list of objects without equals() always recomposed. remember(all) { all.filter { it.unread } } passes the same instance, so it skipped on both, which makes it the fix that does not depend on the compiler.

@Immutable on a wrapper class, or ImmutableList from kotlinx.collections.immutable, makes Compose use equals(), and a wrapper skipped on both versions too. The docs warn that this compares every element on each pass, which can cost more than recomposing a small child.

Warning: Do not add @Stable or @Immutable just to silence a report line. The annotation promises that the value will not change behind Compose’s back. If the class is really mutable, Compose can skip a composable whose data did change, and the screen shows stale values.

(Advanced) Compiler reports and the stability configuration file

Skip this unless a composable is not skipped and you cannot tell why. Reports are turned on per module.

app/build.gradle.kts
composeCompiler {
reportsDestination = layout.buildDirectory.dir("compose_compiler")
metricsDestination = layout.buildDirectory.dir("compose_compiler")
stabilityConfigurationFiles.add(rootProject.layout.projectDirectory.file("stability_config.conf"))
}
Kotlin

The build writes app-classes.txt and app-composables.txt to build/compose_compiler/. The docs recommend a release build for this. Compiling the androidTest sources overwrites the same files, so build only the variant you want to read.

A class from a plain Kotlin/JVM module is compiled without the Compose plugin, so Compose cannot infer its stability. A Money class from a :model module shows up like this.

restartable skippable scheme("[androidx.compose.ui.UiComposable]") fun dev.shippedcode.recompose.Total(
unstable total: Money
)

The configuration file lists classes Compose should treat as stable, one fully qualified name per line.

stability_config.conf
// Classes Compose should treat as stable
dev.shippedcode.model.Money

After a rebuild the line reads stable total: Money. One thing caught me out. With AGP 9.5.2, editing only the .conf file left compileDebugKotlin UP-TO-DATE, and the report did not change until I ran ./gradlew :app:compileDebugKotlin --rerun. List a class only if it really does not change after construction.

(Advanced) Count recompositions in a test

Layout Inspector is interactive, so it cannot catch a regression in CI. The counts in this post came from an instrumented test with a composition tracer. The runtime calls it each time a composable body actually runs, and never for a skipped call.

CompositionCounter.kt
@OptIn(InternalComposeTracingApi::class)
object CompositionCounter : CompositionTracer {
private val counts = ConcurrentHashMap<String, Int>()
fun install() = Composer.setTracer(this)
fun reset() = counts.clear()
fun snapshot(): Map<String, Int> = counts.toSortedMap()
override fun isTraceInProgress() = true
override fun traceEventStart(key: Int, dirty1: Int, dirty2: Int, info: String) {
val name = info.substringBefore(" (")
if (name.startsWith("dev.shippedcode.") && !name.endsWith("<anonymous>")) {
counts.merge(name.substringAfterLast('.'), 1, Int::plus)
}
}
override fun traceEventEnd() = Unit
}
Kotlin

Each scroll step is listState.dispatchRawDelta(10f) followed by waitForIdle(). The API is internal and can change between releases. Keep assertions loose, because lazy row counts vary between runs (MessageRow was 2 in one run and 4 in another).

Gotchas

Warning: Writing state during composition after the same composable has read it causes a loop. In the Android docs example, a counter is incremented after Text("$count"). It composed once and stayed quiet, so a quick check looks fine. After one tap on its button, it recomposed on every frame, 10 times in 10 frames and 73 times after one more simulated second. Write state in callbacks such as onClick, never in the composable body.

Objects created in the composable body without remember, such as formatters, sorted lists or Regex, are rebuilt on every recomposition. Passed to a child, they can also defeat skipping as in Fix 4. Remember them with their inputs as keys, or move them to the ViewModel.

A Log.d inside a composable is a misleading counter. It runs in the nearest restart scope, which may be a parent because Column and Box are inline, it says nothing about skips, and it adds work to what you measure.

The UI state feeding these composables comes from the Android architecture post, and the native vs Flutter guide covers when Compose is the right tool at all. Flutter widgets vs Jetpack Compose maps the same rebuild idea onto Flutter, and state updates arrive through Kotlin coroutines on Android and StateFlow vs SharedFlow.

The next post in the series moves to the data layer with Room in depth: relations, migrations and tests.