Smart recomposition in Jetpack Compose works by so called donut-hole skipping, which leads to only those scopes being recomposed, that need to be (since something might have changed in it). This question is a perfect example on how different layout structuring, wrapping / scoping can prevent unnecessary recompositions.
Take this example:
@Composable
fun Parent(someString: String) {
var someParameter by remember { mutableStateOf(true) }
Column {
Child1()
Child2(someString)
Child3(someParameter)
}
}
If someParameter
would change, not only Child3 would be recomposed, but also the Parent (which I think would also lead to Child2 recomposition because of someString
) since Child3 is not in it is own "capsulated" scope.
To prevent this, I could theoretically put every Child in their own dedicated Scope (wrapping them in another non-inline-fun composable) like this:
@Composable
fun ScopedView(content: @Composable () -> Unit) {
content()
}
@Composable
fun Parent(someString: String) {
var someParameter by remember { mutableStateOf(true) }
Column {
ScopedView { Child1() } }
ScopedView { Child2(someString) }
ScopedView { Child3(someParameter) }
}
}
This seems to solve all those "problems" with unnecessary recompositioning, but I've never seen this kind of approach anywhere during my research. Why? Are there any drawbacks or a better solutions to this?