Why does all the switch get recomposed when only o...
# compose
j
Why does all the switch get recomposed when only one switch is toggled?
Copy code
@Preview(showBackground = true)
@Composable
private fun TogglePreview() {
    val (checked, onCheckedChange) = remember { mutableStateOf(false) }
    val (checked2, onCheckedChange2) = remember { mutableStateOf(false) }
    val (checked3, onCheckedChange3) = remember { mutableStateOf(false) }

    Column() {
        Switch(checked, onCheckedChange)
        Switch(checked2, onCheckedChange2)
        Switch(checked3, onCheckedChange3)
    }
}
Here is the minimal producible code.
c
My guess is it is because of recomposition scopes. Columns is an inline function so it is not a recomposition scope. The next parent composable becomes one so everything within that parent recomposes.
a
how does this even work for you? onCheckedChange is not initialized
j
@Anton Poliakov It is a feature in Jetpack Compose where instead of declare the state as
var checked by remember { mutableStateOf(false) }
And when you try to pass in the lambda from Switch you use
Switch(checked, {checked = it})
You declare it as
val (checked, onChecked) = remember { mutableStateOf(false) }
And in this case you won't need to do the
{checked = it}
Because the onChecked itself is already a lambda
a
oh looks pretty good, thanks for life hack 🙂
j
with type (Boolean) -> Unit
👀 1
c
@Anton Poliakov the official name of the syntax is „destructuring“. It works with I.e. collections as well. https://kotlinlang.org/docs/destructuring-declarations.html
❤️ 1
s
Yeah it's called destructuring, and in short, it's a strictly worse approach compared to doing
by
. https://kotlinlang.slack.com/archives/CJLTWPH7S/p1659553222689339?thread_ts=1659213420.545199&cid=CJLTWPH7S When you use that, you are forcing a read on the declaration itself, completely losing out on any potential wins of deferring the read to a smaller scope and therefore improving performance. I see absolutely 0 reason to use it, and I am honestly surprised why it still is not being discouraged as an approach. Read this https://blog.zachklipp.com/scoped-recomposition-in-jetpack-compose-what-happens-when-state-changes/ for some more details on this. In that example for instance, if you used destructuring you'd then be recomposing everything, including the button due to reading the state at a higher recomposition scope than you would otherwise.
👀 1
❤️ 1
j
I will take a look, thank you!