In Jetpack Compose, when should a checkout screen compute a value with `derivedStateOf` instead of `remember` with keys, and when is `derivedStateOf` wasted or wrong?
answer
- input changes faster than output
- readers recompose only on a new result
- keys are compared with equals
- captured plain values are not tracked
- the derived state must be remembered too
basics
~20 sUse derivedStateOf when fast-changing state feeds a result that changes rarely, such as a scroll offset that only flips a show-total flag; readers recompose only when the result changes. Use remember with keys when inputs and output change together.
solid answer
~50 s`derivedStateOf { }` creates a `State` whose calculation records every snapshot state it reads; when one of them changes, the calculation runs again, but a composable that reads the result is only invalidated if the new result differs from the old one (compared with `==` unless you pass a policy). That is a win when the input changes far more often than the output: a checkout form's `scrollState.value` changes every pixel, while `scrollState.value > thresholdPx` flips once. Wrap it in `remember`, or a new derived state is built on every recomposition. `remember(key1, key2) { }` instead recomputes whenever a key changes, compared with `equals`, which fits inputs that change exactly as often as the output, such as formatting a total from `totalCents`. Two traps: `derivedStateOf` only tracks state reads, so a plain parameter captured in its lambda goes stale unless `remember` is keyed on it; and using it where output changes as often as input only adds overhead.
code
kotlin · 27 linesimport androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
@Composable
fun CheckoutForm(thresholdPx: Int, totalLabel: String) {
val scrollState = rememberScrollState()
val showStickyTotal by remember(thresholdPx) {
derivedStateOf { scrollState.value > thresholdPx }
}
Box {
Column(Modifier.verticalScroll(scrollState)) {
Text("Shipping, payment and the price summary go here")
}
if (showStickyTotal) {
Text(totalLabel, Modifier.align(Alignment.BottomCenter))
}
}
}go deeper
Recall the one-line rule: derivedStateOf when the input changes much more often than the result, remember with keys when they change together.
Explain dependency tracking, caching and result-based invalidation, and why the derived state has to be remembered.
Find the stale-capture bug and the wasted derivedStateOf in review, and justify each choice by how often input and output change on a real screen.
Agree team guidance on when derived state is warranted, so it is not sprinkled everywhere as a performance charm and real hot paths get measured instead.
## The problem: state that changes faster than the UI needs A checkout form is a long `Column` with `Modifier.verticalScroll(scrollState)`. Once the user scrolls past the price summary, a sticky bar with the total should appear. The naive version reads `scrollState.value > thresholdPx` directly in the composable. `scrollState.value` changes on every scrolled pixel, so the composable that reads it is invalidated on every frame of a scroll, although the boolean it cares about changes once. ## How `derivedStateOf` works `derivedStateOf(calculation)` returns a `State<T>` with three behaviours: - **Dependency tracking.** While the calculation runs, every snapshot state it reads is recorded as a dependency. - **Caching.** Reading `.value` repeatedly does not re-run the calculation unless a dependency has changed. - **Result-based invalidation.** When a dependency changes, the calculation runs again. A composable that read the derived state is invalidated only if the new result is not equivalent to the old one. Equivalence uses the policy you pass to the `derivedStateOf(policy, calculation)` overload, or `==` when you pass none. ```kotlin val showStickyTotal by remember(thresholdPx) { derivedStateOf { scrollState.value > thresholdPx } } ``` The calculation still runs on each scroll change; what stops is recomposition of the readers while the result stays `false`. ## How `remember` with keys works `remember(key1, key2) { calculation }` stores the result in the Composition and recomputes it on the next recomposition in which any key differs from the previous one, compared with `equals`. A typical use on the checkout screen is `remember(totalCents, currencyCode) { formatTotal(totalCents, currencyCode) }`: the label must change every time the total changes, so caching per key is all that is needed, and the formatting is skipped on recompositions caused by unrelated state. It does not observe anything by itself: it only runs when the surrounding composable recomposes, which it does because whatever produced the keys changed. | | `derivedStateOf` (inside `remember`) | `remember(keys)` | |---|---|---| | Recomputes when | a snapshot state read inside changes | a key differs at recomposition | | Invalidates readers when | the result changes | the surrounding scope recomposes anyway | | Sees plain parameters | only if `remember` is keyed on them | yes, as keys | | Overhead | snapshot tracking and a cached record | one comparison per key | | Fits | many input changes, few output changes | inputs and output change together | ## Choosing between them 1. Ask how often the **output** changes compared with the **input**. If they change together, `derivedStateOf` buys nothing. 2. If the input is snapshot state that changes often and the output rarely, use `remember { derivedStateOf { } }`. 3. If the inputs are plain values (parameters, constants) and the work is expensive, use `remember(inputs) { }` to avoid recomputing on unrelated recompositions. 4. If both kinds of input are involved, key `remember` on the plain values and read the state inside `derivedStateOf`. ## Classic mistakes - **Capturing a plain parameter.** `remember { derivedStateOf { scrollState.value > thresholdPx } }` captures the first `thresholdPx`. A new threshold is never seen, because it is not state and `remember` has no key that would rebuild the lambda. Key the `remember` on it. - **Forgetting `remember`.** A bare `derivedStateOf { }` in a composable body creates a new derived state on each recomposition, so the cache is thrown away and nothing is saved. - **Using it where output tracks input.** `derivedStateOf { "$firstName $lastName" }` changes whenever either name changes; the extra bookkeeping costs more than recomputing. - **Expecting it to stop the calculation.** It filters invalidation of readers, not evaluation; keep the calculation cheap. - **Reaching for it to defer work to a later phase.** Moving a scroll read into a lambda-based layout or draw modifier is a separate technique, covered with modifiers. ## Where this shows up beyond scrolling The same shape appears whenever a frequently written state feeds a coarse decision: whether a typed promo code is long enough to enable an Apply button when the button sits in another scope, whether a swipe offset has crossed a dismiss threshold, or which section header should be highlighted. In each case the question is the same: does the reader care about every change, or only about a few?
- What goes wrong with `remember { derivedStateOf { scrollState.value > thresholdPx } }` when `thresholdPx` is a plain `Int` parameter?The lambda captures the `thresholdPx` from the first composition. `derivedStateOf` re-runs only when a snapshot state it read changes, and `remember` has no key to rebuild it, so a new threshold is ignored for good. Key `remember` on `thresholdPx`, or pass the threshold as state.
- Why must `derivedStateOf` be wrapped in `remember` inside a composable?Without `remember`, every recomposition creates a new derived state object with an empty cache, so the calculation runs again and readers subscribe to a fresh object each time. The benefit of result-based invalidation disappears.
- What does the `derivedStateOf(policy, calculation)` overload change?The policy decides when a new result counts as different. Without one, composition compares results with `==`; you can pass `referentialEqualityPolicy()` when identity is the right test, or a custom `SnapshotMutationPolicy` when `==` is too expensive or too strict for the result type.
- derivedStateOf is a faster remember and should wrap every computed value
- derivedStateOf notices changes to plain parameters captured in its lambda
- remember with keys recomposes readers only when the computed result changes
- A bare derivedStateOf without remember still caches across recompositions
- derivedStateOf stops the calculation from running when inputs change