derivedStateOf

Jetpack Compose Mid-level Kotlin 2.0+ API 24+ Reviewed By Best Latest Apps

Pick the fix

The whole screen recomposes on every scroll event, but the button only needs to know if the index is above 0. Best fix?

@Composable
fun Feed(listState: LazyListState) {
    val show = listState.firstVisibleItemIndex > 0
    if (show) { Button(onClick = {}) { Text("Top") } }
}
Options
Hint 1 of 1

How often does the Boolean change compared with the index?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A val show by remember { derivedStateOf { listState.firstVisibleItemIndex > 0 } }

Correct. Readers are notified only when the Boolean flips.

Why not the others?
  • B val show = remember { listState.firstVisibleItemIndex > 0 }. That computes once and never updates.
  • C val show = listState.firstVisibleItemIndex > 0 inside a LaunchedEffect. Effects don't return values to the composition.
  • D Move the check into the onClick lambda. Then the button can't be shown or hidden.

30-second answer

Use derivedStateOf when a state changes much more often than the value you derive from it, for example showing a 'Scroll to top' button when the first visible item index is above 0. The derived state only notifies readers when its result changes, so the screen recomposes once when the button appears, not on every scroll event.

Practise saying it · 30 s. No recording, just a timer

Explain when to use derivedStateOf.

Say your answer out loud, then check which of these points you covered:

  • When the input changes more often than the result
  • Wrap in remember
  • Use remember(key) for parameters
  • Pointless when results change as often

Deep dive

Wrap it in remember: val show by remember { derivedStateOf { listState.firstVisibleItemIndex > 0 } }.

If inputs come from parameters rather than state, use remember(key) { } instead.

It's wasted overhead when the derived value changes as often as its input, like fullName = first + last.

It reads state objects, so the block re-runs only when one of those states changes.

Common mistakes

  • Using derivedStateOf for every computed value.
  • Forgetting remember, creating a new derived state every recomposition.
  • Using it with plain parameters that aren't State.

Senior take & follow-ups

Give the 'changes less often than its input' test and one example where it's pointless.

Follow-up questions

Think of your answer first, then open the hint.

  1. When is remember(key) the better tool?

    Show hint

    When the input is a normal parameter, not a State object.

  2. Does derivedStateOf help if the result changes on every input change?

    Show hint

    No, it only adds overhead.

Suggest a fix if something here is wrong or out of date.