Search code examples
kotlinandroid-jetpack-composeandroid-jetpackcompose-recompositionmutablestateof

mutableStateOf holding the value after the recomposition without remember API in Jetpack Compose


Any time a state is updated a recomposition takes place.

but here, I haven't used the remember API, but after the recomposition also it's holding the value, is the mutableStateOf() will remember the value without remember API?

@Composable
fun MyChildUI() {

    var count by mutableStateOf(1)

    Button(onClick = {
        count++
        println(count)
    }) {
        Text(text = "$count")
    }
}

img


Solution

  • This is because of scoped recomposition. Any Composable that is not inline and returns Unit is a scope. Compose only triggers recomposition in nearest scope. In your example it's Button's scope. You can check out this question which is very similar

    Why does mutableStateOf without remember work sometimes?