Why Compose 1.13 Added computedStateOf, and When It Beats derivedStateOf

skydovesJaewoong Eum (skydoves)||20 min read

Why Compose 1.13 Added computedStateOf, and When It Beats derivedStateOf

You have written this line, or one very close to it, in almost every screen that has a list:

val showScrollToTop by remember {
  derivedStateOf { listState.firstVisibleItemIndex > 0 }
}

firstVisibleItemIndex changes many times during a fling, and derivedStateOf keeps the button from recomposing on every change: it recomposes only when the Boolean flips. It works, so nobody questions it. But derivedStateOf was never only a filter. It is also a cache, with its own snapshot records, a dependency map rebuilt on every recalculation, and a snapshot advance after every recalculation. For a single comparison, all of that machinery protects a calculation that costs almost nothing to repeat. Compose runtime 1.13 adds computedStateOf, which keeps the filtering and drops the cache. So what do you give up when the cache disappears, and when is that trade worth taking?

In this article, you'll start from the derivedStateOf you already write and work inward: what computedStateOf promises, how a class with no stored value still lets composition skip, how the layout and draw observer makes the same decision earlier, what the trade looks like when measured on the real runtime, and the patterns where each API wins. The source quotes come from androidx.compose.runtime 1.13.0, and the numbers come from a test program that runs the same runtime on the JVM.

The fundamental problem: derivedStateOf does two jobs

derivedStateOf bundles two features. The first is invalidation filtering: a reader is notified only when the result of the calculation changes, not every time one of its inputs changes. The second is memoization: the result is stored, and later reads return the stored value without running the calculation again, as long as no input has changed.

The scroll button needs the first feature and almost never benefits from the second. Its calculation is one comparison, and the button reads the result once per frame. Yet every recalculation of a DerivedSnapshotState goes through the caching machinery. The real implementation tracks nesting levels and handles more edge cases, but the core of currentRecord looks like this:

val newDependencies = MutableObjectIntMap<StateObject>()
val result = notifyObservers(this) {
    Snapshot.observe({ if (it is StateObject) newDependencies[it] = level }, null, calculation)
}
val record = sync {
    if (policy?.equivalent(result, readable.result as T) == true) {
        readable.dependencies = newDependencies
        readable.resultHash = readable.readableHash(this, Snapshot.current)
        readable
    } else {
        val writable = first.newWritableRecord(this, Snapshot.current)
        writable.dependencies = newDependencies
        writable.resultHash = writable.readableHash(this, Snapshot.current)
        writable.result = result
        writable
    }
}
if (calculationBlockNestedLevel.get()?.element == 0) {
    Snapshot.notifyObjectsInitialized()
}

Each recalculation does four things beyond running your lambda:

  1. A new dependency map: newDependencies is allocated on every recalculation.
  2. A dependency hash: readableHash walks the current record of every direct dependency under the global sync lock, so a later read can compare a hash instead of running the calculation.
  3. A new state record: a derived state is itself a StateObject with a chain of records. The plain derivedStateOf { } overload passes no policy, so policy?.equivalent(...) is never true and every recalculation writes a new record. Only derivedStateOf(policy) { } reuses the record when the result is equivalent.
  4. A snapshot advance: every outermost recalculation ends with Snapshot.notifyObjectsInitialized(), which advances the global snapshot or, inside a mutable snapshot, that snapshot. Only a read only snapshot ignores it. In my test program, each of five recalculations moved the global snapshot id by one, whether the result changed or not, and computedStateOf never moved it. Advances inside one snapshot also accumulate bookkeeping, which matters later.

All of this exists so that a later read can skip the calculation. For firstVisibleItemIndex > 0, the bookkeeping is larger than the work it saves.

computedStateOf: The same filter without the memory

The new factory in runtime 1.13 has the same shape as derivedStateOf:

@StateFactoryMarker
public fun <T> computedStateOf(
    policy: SnapshotMutationPolicy<T> = structuralEqualityPolicy(),
    calculation: () -> T,
): State<T> = ComputedSnapshotState(calculation, policy)

The KDoc spells out the contract, and each line matters in practice:

  • No caching: the calculation runs every time value is read, and it "may be called more times than [State.value] is read as part of managing the state and checking its validity."
  • Conditional invalidation: when a state read inside the calculation changes, a reader is invalidated only if the calculation now returns a value that is not equivalent, under policy, to the last value that reader saw.
  • Read only: the calculation must not write to any state. A write throws an IllegalStateException.
  • No neverEqualPolicy: the KDoc calls it an error, because it defeats every skip.
  • The guidance: prefer it over derivedStateOf "when you don't need the caching behavior that DerivedState provides."

The API first shipped in 1.13.0-alpha03 on September 9, 2026, its API surface was finalized in 1.13.0-beta01 on October 7, and it became stable in 1.13.0 on November 18, as part of the Compose November '26 release (BOM 2026.11.01). The release post goes further than the KDoc: "In general, we recommend using computedStateOf instead of derivedStateOf for state computation." The early builds had real bugs: beta01 added the read only check and fixed a layout and draw path that subscribed scopes straight to a computed state's inputs, bypassing the equality check, and beta02 fixed a leak that kept a computed state's recorded values alive, along with a missed invalidation when the calculation calls Snapshot.withoutReadObservation. Use 1.13.0, and check what your build resolves: navigation3-ui 1.3.0-alpha03 and alpha04 depend on runtime 1.13.0-alpha03, and since Gradle picks the highest requested version, adding either one to an app on an older stable runtime pulls in alpha03 without those fixes. Version 1.3.0-alpha05 depends on Compose Animation 1.14.0-alpha01 instead, which moves runtime and UI to 1.14.0-alpha01 even on BOM 2026.11.01.

For the scroll button, the migration is one word:

val showScrollToTop by remember {
  computedStateOf { listState.firstVisibleItemIndex > 0 }
}

What the user sees does not change. The button still recomposes only when the Boolean flips. What changes is the work between those flips.

Inside ComputedSnapshotState

The whole implementation fits on one screen. Looking at the class in 1.13.0, without its comments and debugger helpers:

private class ComputedSnapshotState<T>(
    private val calculation: () -> T,
    override val policy: SnapshotMutationPolicy<T>,
) : ComputedState<T> {

    override val value: T
        get() {
            Snapshot.current.readObserver?.invoke(this) ?: return Snapshot.readOnly(calculation)
            return Snapshot.readOnly {
                notifyObservers(this, calculation)
            }
        }

    override fun isInvalidFor(previousValue: T): Boolean {
        return !policy.equivalent(
            Snapshot.withoutReadObservation { Snapshot.readOnly(calculation) },
            previousValue,
        )
    }
}

Notice what is missing. ComputedSnapshotState does not extend StateObjectImpl. It has no state records, no dependency list, and no stored result. It is a State<T> around a lambda, plus two hooks that the runtime knows how to call.

The getter reports the read to whoever is observing, composition or the layout and draw observer, then runs the calculation inside Snapshot.readOnly: a reusable pseudo snapshot that forwards reads to the current snapshot and throws on any write. If nobody is observing, as in a click handler, it skips the notification and runs the calculation, still read only. notifyObservers brackets the calculation with start and done callbacks, which is how an observer learns which reads belong to the calculation and what value it produced.

isInvalidFor is the other half. Given the value a reader saw last time, it runs the calculation again with read observation turned off and compares the two results with the policy. Both skipping paths below end up calling it.

The read only rule is enforced. In my test program, a calculation that incremented another mutableIntStateOf threw IllegalStateException: Cannot modify a state object in a read-only snapshot, while the same lambda inside derivedStateOf let the write through. This is the one part of a migration that is not mechanical: a derivedStateOf that writes to snapshot state, even a debug counter in a mutableStateOf, crashes after the switch.

How composition skips without a stored value

If the computed state stores nothing, the last value a reader saw has to live somewhere else. It lives in the reader's RecomposeScopeImpl. Let's trace a read inside a composable.

When the getter calls readObserver, composition lands in CompositionImpl.recordReadOf. It records the read against the current scope as usual, then sets currentComputedState = value to mark the state whose calculation is about to run. Every read during the calculation comes back into the same function and takes an early branch at its top. The real branch also flattens the dependencies of a derived state read inside the calculation, which is left out here:

val currentComputingState = currentComputedState
if (currentComputingState != null) {
    if (value is StateObjectImpl) {
        value.recordReadIn(ReaderKind.Composition)
    }
    indirectStates.add(value, currentComputingState)
    return
}

The inputs are not recorded as reads of the scope. They are mapped to the computed state in indirectStates. When the calculation finishes, the done callback stores the result in the scope:

override fun done(state: IndirectState<*>, calculatedValue: Any?) {
    if (state === currentComputedState && --currentComputedStateReentrantDepth == 0) {
        composer.currentRecomposeScope?.recordDerivedStateValue(state, calculatedValue)
        currentComputedState = null
    }
}

After the first composition, the scope knows "I read this computed state and saw true", and the composition knows "this computed state depends on firstVisibleItemIndex". The method name recordDerivedStateValue gives away the design: the slot that derivedStateOf already used for its last seen value now serves both APIs.

Now the user keeps scrolling, and firstVisibleItemIndex goes from 3 to 4:

  1. Conditional invalidation: when the change is applied, composition finds the computed state through indirectStates, then the scopes that read it. Each of them has a recorded value, so it is invalidated conditionally.
  2. The check: on the next frame, the composer reaches the invalidation and calls isInvalid(), which calls isInvalidFor(true) on the computed state. The calculation runs, returns true, and the policy says nothing changed. The scope is skipped.
  3. The reread: because the scope was skipped, the composer calls rereadTrackedInstances().

Looking at rereadTrackedInstances:

trackedInstances.forEach { value, _ ->
    if (value is ComputedState<*>) {
        value.value
    } else {
        owner.recordReadOf(value)
    }
}

The composer rereads every tracked instance of a skipped scope so that the composition's tracking stays current. A derived state replays its stored dependency list through recordReadOf. A computed state has no list to replay, so it reads value: composition drops the computed state's old dependency set, and the calculation runs a second time to record the current one. This is also what keeps a calculation that reads different states on different branches subscribed to the right ones.

This is the price of having no cache, and a counter shows it plainly. In my test, one composable read a threshold over a state that changed 1,000 times and crossed the threshold once:

  • Direct read (offset > 300 in the body): 1,000 recompositions.
  • derivedStateOf: 1 recomposition and 1,000 calculations.
  • computedStateOf: 1 recomposition and 2,000 calculations.

In composition, computedStateOf pays two calculations per reading scope for every frame in which an input changed, however many writes came before that frame: five writes per frame still gave 2,000 calculations for 1,000 frames. For a comparison, that costs nanoseconds. For a calculation that filters a list, it can cost the whole frame.

Layout and draw: The check runs before anything is invalidated

Composition is not the only reader. Reads inside layout modifiers, graphicsLayer blocks and draw modifiers are tracked by Compose UI's OwnerSnapshotObserver, which wraps a SnapshotStateObserver.

SnapshotStateObserver makes the skip decision earlier, at the moment changes are applied. Looking at recordInvalidation:

dependencyToIndirectStates.forEachScopeOf(value) { indirectState ->
    indirectState as IndirectState<Any?>
    val previousValue = recordedIndirectStateValues[indirectState]

    // Invalidate only if currentValue is different than observed on read
    if (indirectState.isInvalidFor(previousValue)) {
        valueToScopes.forEachScopeOf(indirectState) { scope ->
            invalidated.add(scope)
            hasValues = true
        }
    } else {
        // Re-read state to ensure its dependencies are up-to-date
        statesToReread.add(indirectState)
    }
}

If the result did not change, the layout or draw scope is never invalidated: no remeasure, no redraw for that node. The state goes on a reread list to refresh its dependencies, which runs the calculation once more. The last seen value is kept once per computed state in each phase's observer map, and Compose UI keeps separate maps for measure, layout, draw and semantics. So this check costs two calculations for every changed input in every apply notification, in every phase that reads the state, but it does not grow with the number of scopes in one phase. With a draw style scope over the same 1,000 changes:

  • Direct read: 1,000 invalidations.
  • derivedStateOf: 1 invalidation and 1,000 calculations.
  • computedStateOf: 1 invalidation and 2,000 calculations.

With three draw scopes reading the same computed state, the count barely moved, to 2,002. When both inputs of the calculation changed in the same apply, or when the state was read in two phases, it doubled to 4,000, while derivedStateOf stayed at 1,000 by answering the repeated checks from its cache. derivedStateOf gets the same early skip on this path, so what computedStateOf changes here is the cost of each applied change: 160 bytes allocated against 336 in my test. Reading a coarse value only in the draw phase is a good pattern with either API. A divider under the top bar that appears once the list is scrolled:

@Composable
fun ConversationList(conversations: List<Conversation>, modifier: Modifier = Modifier) {
  val listState = rememberLazyListState()
  val showDivider by remember {
    computedStateOf { listState.firstVisibleItemIndex > 0 || listState.firstVisibleItemScrollOffset > 0 }
  }
  LazyColumn(
    state = listState,
    modifier = modifier.drawWithContent {
      drawContent()
      if (showDivider) drawLine(Color.LightGray, Offset.Zero, Offset(size.width, 0f))
    },
  ) {
    items(conversations, key = { it.id }) { ConversationRow(it) }
  }
}

showDivider is read only inside the draw lambda, so ConversationList never recomposes for it. The scroll offset changes on every frame of a fling, yet the draw scope is invalidated only when the divider appears or disappears, and the check between those moments allocates about as much as a plain state read.

Measuring the trade

The counts above are exact. For time and memory, I ran the same program with timers: a JVM process (JDK 21 on an Apple M4 Max), runtime-desktop 1.13.0-rc01 (whose sources are identical to 1.13.0), Kotlin 2.4.21, and a real Recomposer driven frame by frame, using the plain derivedStateOf { } overload. Each case was warmed up, measured in five to nine rounds, and run twice in opposite orders, with allocation read from the thread's allocated bytes counter. A second program, written separately, reproduced the core counts, matched the 200 row computedStateOf allocation to the byte, and matched derivedStateOf within 0.1%. Two limits apply: JVM timings are not device frame times, so read the ratios, and the test composables have empty bodies, so recomposition costs almost nothing here, which flatters the direct read.

  • One reader, result unchanged: the time difference stayed inside the noise, with no consistent winner, both in composition (0.8 to 1.5 µs per frame across runs) and in the layout and draw path (about 0.25 µs). Allocation did differ: in composition, computedStateOf allocated 1,968 bytes per frame against 2,328 to 2,352 for derivedStateOf, and in the layout and draw path 160 bytes against 336, close to the 152 bytes of a plain state read.
  • A list where every row has its own isSelected state, one composition per row: this is how lazy layouts work, since each item is its own subcomposition and the Recomposer recomposes each composition in its own snapshot. Per selection change, derivedStateOf allocated about 1.42 KB per row, computedStateOf about 1.04 KB, and a direct read about 1.07 KB, flat from 50 to 800 rows. At 200 rows, a frame took about 174 µs, 159 to 164 µs, and 135 µs.
  • The same rows inside one composition, as in a Column without laziness: every recalculation advances the same snapshot, and the cost of derivedStateOf grows with the row count. Per frame, it allocated 20 KB at 50 rows, 137.5 KB at 200, and 2.6 MB at 800. computedStateOf allocated 4.7 KB, 12.2 KB and 42.8 KB. At 800 rows, a frame took 430 to 443 µs against 271 to 276 µs.
  • First composition: inside one composition, the creation cost of derivedStateOf grows the same way, from 1,121 bytes per item at 100 items to about 4.9 KB at 1,000, while computedStateOf stayed at 650 to 700 bytes. With one composition per row, the difference was about 500 bytes per row.
  • The flip side: a filter over 10,000 strings, read by three composables that recompose on every frame for an unrelated reason. derivedStateOf ran the filter once at first composition and never again during 200 frames, at 1 to 11 µs per frame. computedStateOf ran it 600 times, at 0.62 to 0.83 ms per frame. This case was a single 200 frame run without warmup, repeated three times.

For a single reader, the gain from computedStateOf is allocation rather than time. It becomes large where many derived states recalculate inside one composition, and it reverses where an expensive result is read more than once.

Practical patterns

Thresholds over fast changing values

Scroll position, drag offset, gesture progress and window size change continuously, while the UI usually cares about a coarse answer. Since navigation3-ui 1.3.0-alpha03, NavDisplay tracks the predictive back gesture this way:

val inPredictiveBackGesturePhase by
    remember(previousScene, navigationEventState) {
        computedStateOf {
            navigationEventState.transitionState is InProgress && previousScene != null
        }
    }

transitionState gets a new value on every event of the gesture, and the commit that switched this from derivedStateOf gives the reason: "to reduce per-frame allocation overhead during predictive back gestures."

Look at the remember keys. previousScene is a plain value captured by the lambda, which the computed state cannot observe, so without the key the lambda would keep the first previousScene forever. The rule is the same as with derivedStateOf: every captured value that can change between recompositions must be a key. The scroll button needs none only because its listState never changes.

When the captured value is a parameter that changes often, such as a lambda, recreating the state on every change is wasteful. Wrap the parameter with rememberUpdatedState and read it inside the calculation instead, which turns it into an ordinary dependency. The new computedMediaQuery in Compose UI 1.14.0-alpha01, which deprecates derivedMediaQuery, is built exactly this way: remember(mediaScope) { computedStateOf { mediaScope.currentQuery() } }, where currentQuery comes from rememberUpdatedState(query).

Properties on state holders

computedStateOf does not need a composable. In Compose Foundation 1.14.0-alpha01, ScrollState.canScrollForward is now computedStateOf { value < maxValue }, and PagerState.settledPage and targetPage made the same switch. The pattern works the same way in your own state holders:

@Stable
class CheckoutFormState {
  var email by mutableStateOf("")
  var cardNumber by mutableStateOf("")
  var isSubmitting by mutableStateOf(false)

  val canSubmit by computedStateOf {
    !isSubmitting && email.contains('@') && cardNumber.length == 16
  }
}

Every keystroke changes email or cardNumber, but a submit button that reads canSubmit recomposes only when the answer flips. The property needs no remember, because the state holder itself is created once.

BasicTextField in 1.14.0-alpha01 uses the same shape to combine field focus and window focus: computedStateOf { isFocused && windowInfo.isWindowFocused }.

One flag per row

A row that highlights itself when selected is the classic case for one small state per item:

@Composable
fun ConversationRow(conversation: Conversation, selection: SelectionState) {
  val isSelected by remember(selection, conversation.id) {
    computedStateOf { selection.selectedId == conversation.id }
  }
  Text(
    text = conversation.title,
    fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal,
  )
}

When the selection changes, every row runs its comparison, and only the two rows whose answer changed recompose. Inside a LazyColumn, each row is its own subcomposition with its own snapshot, so the saving is modest: about 380 bytes per row per selection change in my test. Where the switch pays off most is a single composition in which many derived states recalculate in the same frame, such as a long Column, or many flags on one screen that depend on the same fast changing state. There, the snapshot advances of derivedStateOf pile up in one snapshot, and the allocation gap grew from 4x at 50 rows to 60x at 800.

When derivedStateOf is still the right tool

The androidx changes describe their targets as calculations that "don't seem to benefit from the caching", and the deprecation message for derivedMediaQuery speaks of "trivial calculations". Both qualifiers matter. computedStateOf is the wrong choice in these cases:

  • The calculation is expensive. Filtering, sorting or formatting a collection runs again on every read and twice for every change. Keep the cache:
val visibleProducts by remember(products) {
  derivedStateOf { products.filter { it.name.contains(searchQuery.value, ignoreCase = true) } }
}
  • Several composables read a result that is not trivial. In composition, each reading scope runs the calculation twice per frame with a change: with three readers over 1,000 changes, computedStateOf ran it 6,000 times and derivedStateOf 1,000 times. The layout and draw path multiplies it by phases and by inputs that change together. For a cheap comparison, this is a trade rather than a loss: with three readers, computedStateOf took 4 to 8% more time per frame and allocated about 15% less, and with ten readers about 25% more time. As the calculation gets heavier, the multiplied runs decide it.
  • A child depends on the result's identity. When the calculation allocates, computedStateOf hands back a new instance on every read, and under strong skipping a parameter whose type the compiler reports as unstable is compared by identity. In my test, a parent recomposed 100 times for an unrelated reason, and a child taking an unstable Selection class recomposed 100 times with computedStateOf and 0 times with derivedStateOf, which returned its cached instance. That protection lasts only until an input changes: with an input that changed every frame and an equal result, the plain derivedStateOf { } stored a new instance too, and only derivedStateOf(structuralEqualityPolicy()) { } kept the child at 0. A List<String> parameter, compared with equals here, skipped in every case on Kotlin 2.4.21.
  • The result changes as often as its input. computedStateOf { offsetPx / 2 } reports a change on every check, so the scope recomposes anyway after running the calculation twice. Read the state directly. A neverEqualPolicy has the same effect: in my test it produced 1,000 recompositions for 1,000 changes, which is why the KDoc treats it as an error.
  • The calculation writes state. As shown earlier, it throws, where derivedStateOf let the write through.

One rule does not change between the two APIs. computedStateOf carries @StateFactoryMarker, the annotation that the UnrememberedMutableState lint check looks for, so creating one inside a composable without remember is reported as an error, just as it is for derivedStateOf.

Conclusion

In practice, the habit to build is asking what a derivedStateOf is for before you write one. If it exists to keep a reader from updating on every small change, and the calculation is a cheap read only mapping, computedStateOf gives you the same skipping for less memory, and for much less when many of them recalculate in one composition. If the result is expensive to produce, read by many composables at once, or handed to children that compare it by identity, the cache is what you are paying for, so keep it. When you migrate, check what the one word change hides: no snapshot writes in the calculation, a calculation cheap enough to run twice per change, remember keys for every captured value that can change, and a build that resolves runtime 1.13.0 or later.

derivedStateOf answered two questions with one API: should this reader update, and have I computed this already? computedStateOf answers only the first, and it can do that without storing anything because the reader's scope already holds the last value it saw. The runtime simply asks the calculation again. Once you see the two questions separately, the choice stops being a performance trick and becomes a plain question about your calculation: is it cheaper to repeat, or to remember?

As always, happy coding!

— Jaewoong (skydoves)