Middle+
How to reduce the number of recompositions in an application besides using side effects?
sobes.tech AI
Answer from AI
Use remember.
Apply stable data types (marked with @Stable or @Immutable).
Delegate calculations:
// Avoid recalculations on every recomposition
val myExpensiveValue by remember {
derivedStateOf {
calculateExpensiveValue()
}
}
Use lambdas that capture the minimum number of variables:
// Lambda will be recreated only when count changes
Button(onClick = { onCountChanged(count + 1) }) {
Text("Increment")
}
Apply Composable functions with the minimum number of parameters.
Use Composable with @MovableContentOf if you need to move a subtree of Compose without recomposition.
Use composite keys (key) for lists if more precise matching of elements is required during changes.
Avoid calling non-stable functions within a Composable.