Is compose smart enough to only re-compose UI elem...
# compose
k
Is compose smart enough to only re-compose UI elements that use fields from a data class that are partially updated? In the example below, if I change the username in the
TextField
does compose only update
NameUI
or does it also re-compose
AgeUI
since state updated and it includes the value for
AgeUI
.
Copy code
private data class State(
    var name: String = "",
    var age: Int = 0,
)

@Composable
fun UI() {
    val state = remember { State() }

    NameUI(name = state.name, onNameChange = { state.name = it })
    AgeUI(age = state.age, onAgeChange = { state.age = it })
}

@Composable
private fun NameUI(name: String, onNameChange: (String) -> Unit) {
    TextField(value = name, onValueChange = onNameChange)
}

@Composable
private fun AgeUI(age: Int, onAgeChange: (Int) -> Unit) {
    TextField(value = age.toString(), onValueChange = { onAgeChange(it.toInt()) })
}
1
s
You need to make both
name
and
age
a
MutableState
first. After doing so, the answer is yes, e.g.
AgeUI
wont't recompose if
name
changes (
UI
and
NameUI
will), because it doesn't read
name
and it's
Stable
K 2
2
However, you can verify the recompositions yourself using the layout inspector provided by android studio electric eel
👀 2
k
Thanks!
a
As ste said, the fields need to be MutableState so that they can recompose their composable. What I'm curious about is whether placing MutableState fields inside a data class is a good practice or not. Are such data classes restricted to be used in only compose? Are there any other common issues?
g
Also is recomposition means relayout and rerender ? If the Compose tree is partially recomputed but only one textview is invalidated/redrawn, then it's a question of UI hyper-performance vs code simplicity (for a case where a data class contains just a few fields that doesn't change every seconds).
👀 1