@Composable
fun MyComposable() {
// Store the value of count using remember
var count by remember { mutableStateOf(0) }
// Compute the derived state based on count
val doubledCount by
derivedStateOf {
println("MainActivity:MyComposable:derivedStateOf")
count * 2
}
Column {
// Update the count when a button is clicked
Button(onClick = { count++ }) {
Text("Increment Count: $count")
}
// Display the derived state
Text("Doubled Count: $doubledCount")
}
}
Even though
derivedStateOf
’s body called twice (because we don’t have
remember
around it), the value is correct.
• Why (or how?) is this happening?
• Why there’s no infinite recomposition? 👀
Think about the derived state as a lambda that caches the return value if inputs (states) didn't change
If you don't memoize such lambda, it is still going to evaluate correctly, you just won't get caching benefits
shikasd
06/14/2023, 12:31 AM
There's a bit more to it in this case, e.g. it is slightly more expensive for recomposition, as it has to track new states each time
And also you don't need a derived state here at all, tbh, as count changes as often as doubled count
t
theapache64
06/14/2023, 12:42 AM
Understood. This is a minimised version to repro the issue. Thanks 🙂