```@Composable fun MyComposable() { // Store t...
# compose
t
Copy code
@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? 👀
s
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
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
Understood. This is a minimised version to repro the issue. Thanks 🙂