Search code examples
androidandroid-jetpack-composecompose-recomposition

What does Jetpack Compose remember actually do, how does it work under the hood?


Checking out codelab's basic tutorial there is a snippet to increase counter on button when clicked

@Composable
fun MyScreenContent(names: List<String> = listOf("Android", "there")) {
    val counterState = remember { mutableStateOf(0) }

    Column(modifier = Modifier.fillMaxHeight()) {
        Column(modifier = Modifier.weight(1f)) {
            for (name in names) {
                Greeting(name = name)
                Divider(color = Color.Black)
            }
        }
        Counter(
            count = counterState.value,
            updateCount = { newCount ->
                counterState.value = newCount
            }
        )
    }
}


@Composable
fun Counter(count: Int, updateCount: (Int) -> Unit) {
    Button(
        onClick = { updateCount(count + 1) },
        colors = ButtonConstants.defaultButtonColors(
            backgroundColor = if (count > 5) Color.Green else Color.White
        )
    ) {
        Text("I've been clicked $count times")
    }
}

It is clear that remember { mutableStateOf(0) } stores the state/value. My question is what remember does under the hood. Using var count = remember { 0 } or mutableStateOf(0) without remember does not increase the value.

fun MyScreenContent(names: List<String> = listOf("Android", "there")) {
   
    var count = remember { 0 }

    Column(modifier = Modifier.fillMaxHeight()) {
        Column(modifier = Modifier.weight(1f)) {
            for (name in names) {
                Greeting(name = name)
                Divider(color = Color.Black)
            }
        }
        Counter(
            count = count,
            updateCount = { newCount ->
                count = newCount
            }
        )
    }
}

Snippet above does not update the value printed on Text, does remember only work with MutableState?


Solution

  • remember - just allows you to remember state from a previous recompose invocation. So, if you for instance randomize color at initial run. The randomized color is going to be calculated only once and later reused whenever re-compose is necessary.

    And hence,

    remember = store the value just in case recompose is called.

    Now, the second important thing is knowing when reCompose should actually be triggered and there the mutable states come to help.

    mutablestate = store the value and in case I update value trigger, recompose for all elements using this data.