DEV Community

Cover image for Skip the Cache: When computedStateOf Beats derivedStateOf in Compose
Android Expert
Android Expert

Posted on Originally published at Medium

Skip the Cache: When computedStateOf Beats derivedStateOf in Compose

Most Compose developers learn one rule early: if a composable only needs to react to a threshold or a condition on fast-changing state, wrap that condition in derivedStateOf. The classic case is a "scroll to top" button that should flip when firstVisibleItemIndex crosses a line, not on every scroll pixel.

Starting with Compose Runtime 1.13.0-beta01, there is a second option: computedStateOf. It has the same goal as derivedStateOf (fewer unnecessary recompositions) but a different cost model. It is reported to perform better in most cases, and for simple conditions it is reported to be about three times faster.

This post covers why that happens, where the rule flips, and the failure modes that will bite you in production.

The one difference that matters

Both functions return a State<T> whose reads are tracked by the snapshot system. The difference is what happens on a read:

  • derivedStateOf caches its value. It re-runs the lambda only when something it depends on has changed.
  • computedStateOf does not cache. It runs the lambda on every read.

read-path

Intuition says the cached version must win. Reality is less kind to caches: maintaining the cache is not free. The runtime has to record dependencies, check whether they changed, store the result, and keep readers informed. When the lambda itself is a comparison or a bit of arithmetic, that bookkeeping can cost more than just running the lambda again.

One caveat on the diagram: it is a simplification. computedStateOf still takes part in snapshot read tracking, so readers can be invalidated when its result changes, and the exact split of bookkeeping between clean reads and invalidations is an implementation detail I haven't verified. The reliable takeaway is the trade-off, not the precise accounting.

That is the entire story, and it explains both the speedup and the limits of the speedup.

Where the cost lands

cost-model

The graphic uses illustrative units, not measurements. The shape is what matters:

  • Cheap lambda, few reads: upkeep dominates, so dropping the cache wins.
  • Expensive lambda, repeated reads: the cache earns its keep, because without it the heavy work repeats on every read.

Example 1: a “jump to latest” button (use computedStateOf)

A chat screen shows a floating button once the user has scrolled away from the newest message. The lambda is one integer comparison.

@Composable
fun ChatScreen(
    messages: List<ChatMessage>,
    onJumpToLatest: () -> Unit,
) {
    val listState = rememberLazyListState()

    val showJumpButton by remember(listState) {
        computedStateOf { listState.firstVisibleItemIndex > 2 }
    }

    Box(Modifier.fillMaxSize()) {
        LazyColumn(state = listState, reverseLayout = true) {
            items(messages, key = { it.id }) { MessageRow(it) }
        }
        AnimatedVisibility(
            visible = showJumpButton,
            modifier = Modifier.align(Alignment.BottomEnd),
        ) {
            JumpToLatestButton(onClick = onJumpToLatest)
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

The lambda reads one snapshot-backed property and compares it to a constant. There is nothing worth caching, so the cache machinery is pure overhead.

Example 2: form validity (use computedStateOf)

@Composable
fun SignUpForm(onSubmit: (String, String) -> Unit) {
    var email by rememberSaveable { mutableStateOf("") }
    var password by rememberSaveable { mutableStateOf("") }

    val canSubmit by remember {
        computedStateOf { email.isNotBlank() && password.length >= 10 }
    }

    Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
        OutlinedTextField(email, { email = it }, label = { Text("Email") })
        OutlinedTextField(password, { password = it }, label = { Text("Password") })
        Button(onClick = { onSubmit(email, password) }, enabled = canSubmit) {
            Text("Create account")
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Two cheap string checks. Again: no allocation, no iteration, no cache needed.

Example 3: a grouped, filtered catalog (stay with derivedStateOf)

Now flip the situation. Here the lambda filters a collection and builds a new map, and the result feeds several composables.

@Composable
fun CatalogScreen(products: SnapshotStateList<Product>) {
    var query by remember { mutableStateOf("") }

    val sections: Map<Category, List<Product>> by remember {
        derivedStateOf {
            products
                .filter { it.name.contains(query, ignoreCase = true) }
                .groupBy { it.category }
        }
    }

    Column {
        SearchField(query) { query = it }
        SectionHeaderRow(categories = sections.keys)   // reads the result
        CatalogList(sections)                          // reads it again
        EmptyStateOrSummary(totalMatches = sections.values.sumOf { it.size })
    }
}
Enter fullscreen mode Exit fullscreen mode

Three readers, a filter, a grouping, and fresh Map and List objects. With computedStateOf, every read would redo the filter and the grouping and allocate new collections. The cache in derivedStateOf is doing real work here, so it is worth its cost.

Example 4: combine them

A good pattern for senior teams: let derivedStateOf own the expensive computation, then use computedStateOf for the cheap flag derived from it.

val sections by remember { derivedStateOf { products.filter(::matchesQuery).groupBy { it.category } } }

val showEmptyState by remember { computedStateOf { sections.isEmpty() } }
Enter fullscreen mode Exit fullscreen mode

The heavy work is computed once per change; the cheap boolean skips the cache.

Choosing between them

decision-guide

In short:

  • Simple conditions or comparisons: computedStateOf.
  • Heavy calculations or code that creates new objects: derivedStateOf.
  • Unsure: measure on real hardware, not on a flagship emulator.

Failure modes you will actually hit

failure-modes

1. Heavy work hidden in a “simple” lambda

The most common mistake is a lambda that looks small but calls something expensive.

// Looks harmless. Is not.
val hasUnread by remember {
    computedStateOf { messages.any { it.isUnread && it.matches(filter) } }
}
Enter fullscreen mode Exit fullscreen mode

any walks the list, and matches might run a regex. Without a cache, that cost repeats for every read, on every recomposition of every reader. If the list is long or matches is non-trivial, move this to derivedStateOf, or better, compute it once in the ViewModel.

2. Allocating inside the block

// Allocates a new List on every read.
val pinned by remember { computedStateOf { tags.filter { it.pinned } } }
Enter fullscreen mode Exit fullscreen mode

Two problems at once: allocation pressure on a hot path, and a new instance per read. If the element type does not implement structural equality, consumers can see “a different value” each time. Even when equality saves you, the allocation itself is the cost you were trying to avoid. This is exactly the “code that creates new objects” case, so use derivedStateOf (or hoist the work out of composition).

3. Writing state inside the calculation

The calculation block is enforced as read-only as of 1.13.0-beta01. Mutating state inside it throws an IllegalStateException.

var attempts by remember { mutableIntStateOf(0) }

// Throws at runtime: the block must only read.
val locked by remember {
    computedStateOf { attempts++; attempts > 3 }
}
Enter fullscreen mode Exit fullscreen mode

This was always bad practice for derived state; now it fails loudly. Because the lambda can run on every read, side effects here would have been especially unpredictable. Keep the block pure, and move mutations into event handlers or effects.

4. Pinning to an early build

The 1.13 line has already shipped several computedStateOf fixes: unexpected invalidations when read through SnapshotStateObserver (beta01), a memory leak in ComputedState that could keep recorded state values from being released, and invalidation not firing correctly when the block called Snapshot.withoutReadObservation (both beta02). If you adopted it from beta01, move to the latest 1.13 build before drawing conclusions from your results.

5. Trusting a benchmark that does not match your screen

A microbenchmark on a flagship device will favor whichever option has less fixed overhead. Your real screens read these values from several composables, during scroll, on mid-range hardware. Use a recomposition probe while you experiment:

@Composable
fun RecompositionProbe(tag: String) {
    val count = remember { intArrayOf(0) }
    SideEffect { Log.d("Recomposition", "$tag -> ${++count[0]}") }
}
Enter fullscreen mode Exit fullscreen mode

Drop it into the composables that read the state, scroll or type through the screen, and compare counts and frame timing across both implementations. For frame-level evidence, run a Macrobenchmark against a release-like build.

A migration checklist

  1. Grep for derivedStateOf in your codebase and sort the hits by lambda weight.
  2. For single comparisons against a constant (> 2, isNotBlank(), == null), try computedStateOf.
  3. For anything that filters, sorts, maps, groups, or builds a new object, leave it alone.
  4. Confirm the block does not write state.
  5. Verify on a mid-range device, comparing recomposition counts and frame timing.
  6. Use the latest 1.13 build (1.13.0-rc01 at the time of writing, still a release candidate), and plan for the Kotlin 2.2 requirement.

🔚 Takeaway

derivedStateOf caches, computedStateOf doesn't, and the cache has a price. When the lambda is a trivial condition, skipping the cache is cheaper. When the lambda is heavy or allocates, the cache pays for itself. Pick based on what the lambda actually does, not on which API looks smarter.

📱 Stop Guessing Whether Your Android Code Actually Works

If “we’ll add tests later” is a sentence your team says a little too often, I’d recommend “Mastering Android Testing” — a 35-chapter deep dive into why Android testing is uniquely hard (Activity/Fragment coupling, async complexity, tooling churn) and exactly how to fix it, layer by layer. It walks through architecting for testability, JUnit/Truth/MockK fundamentals, ViewModel and coroutine/Flow testing without flakiness, Compose UI testing and the semantics tree, Espresso and instrumented tests, Room/Retrofit data-layer testing with a full sync-conflict-resolution case study, Robolectric’s real limits, CI pipelines, flaky test triage, and how to build a testing culture that actually survives contact with a deadline.

Top comments (0)