Challenge - 5 Problems
Derived State Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ ui_behavior
intermediate2:00remaining
How does derived state update the UI?
Consider a Compose UI with a derivedStateOf that calculates the length of a text input. What happens when the user types a new character?
Android Kotlin
val text = remember { mutableStateOf("") }
val textLength = remember { derivedStateOf { text.value.length } }
TextField(value = text.value, onValueChange = { text.value = it })
Text(text = "Length: ${textLength.value}")Attempts:
2 left
💡 Hint
Derived state recalculates when its dependencies change.
✗ Incorrect
derivedStateOf tracks dependencies like text.value and updates its value immediately when text changes, so the UI shows the new length right away.
❓ lifecycle
intermediate2:00remaining
When is derivedStateOf recomputed?
Given a derivedStateOf that depends on multiple mutable states, when does it recompute its value?
Android Kotlin
val count = remember { mutableStateOf(0) }
val enabled = remember { mutableStateOf(true) }
val derived = remember {
derivedStateOf {
if (enabled.value) count.value * 2 else 0
}
}Attempts:
2 left
💡 Hint
Derived state tracks all state reads inside its block.
✗ Incorrect
derivedStateOf recomputes only when any of the states it reads (count.value or enabled.value) change, avoiding unnecessary recomputations.
🔧 Debug
advanced2:00remaining
Why does derivedStateOf not update as expected?
A developer uses derivedStateOf but notices the UI does not update when the base state changes. What is the most likely cause?
Android Kotlin
val baseState = mutableStateOf(0) val derived = derivedStateOf { baseState.value * 2 } // UI uses derived.value but does not recompose on baseState changes
Attempts:
2 left
💡 Hint
Compose only recomposes when observed state is read in the UI.
✗ Incorrect
If the UI does not read derived.value, Compose does not know to recompose when derived changes, so the UI stays stale.
🧠 Conceptual
advanced2:00remaining
Why use derivedStateOf instead of recomputing directly in UI?
What is the main advantage of using derivedStateOf for computed values in Compose?
Attempts:
2 left
💡 Hint
Think about avoiding unnecessary work in UI updates.
✗ Incorrect
derivedStateOf caches the computed value and only recalculates when its dependencies change, reducing unnecessary recompositions and improving performance.
📝 Syntax
expert2:00remaining
Identify the correct syntax for derivedStateOf usage
Which option shows the correct way to declare a derivedStateOf that depends on a mutableStateOf in Compose?
Attempts:
2 left
💡 Hint
derivedStateOf takes a lambda returning the computed value.
✗ Incorrect
derivedStateOf requires a lambda block that returns the computed value. Accessing count.value inside the lambda tracks the dependency.