Introduction to Android.pdf
735.5 KB
One app for all your Word, Excel, PowerPoint and PDF needs. Get the Microsoft 365 Copilot app: https://aka.ms/GetM365
Using State Inside Loops
🚫 Bad Code
@Composable
fun BadLoop() {
repeat(3) {
var text by remember { mutableStateOf("") } // ❌ state recreated in each recomposition
TextField(value = text, onValueChange = { text = it })
}
}
✅ Good Code@Composable
fun GoodLoop() {
val texts = remember { mutableStateListOf("", "", "") } // ✅ stable list of states
texts.forEachIndexed { index, text ->
TextField(value = text, onValueChange = { texts[index] = it })
}
}
✔ Fix: Use mutableStateListOf for lists of states.
✅ In this batch we covered State Management best practices:
remember vs rememberSaveable
derivedStateOf for derived values
Avoiding passing raw MutableState
Stable keys in lists
State hoisting
🚫 Bad Code
@Composable
fun BadLoop() {
repeat(3) {
var text by remember { mutableStateOf("") } // ❌ state recreated in each recomposition
TextField(value = text, onValueChange = { text = it })
}
}
✅ Good Code@Composable
fun GoodLoop() {
val texts = remember { mutableStateListOf("", "", "") } // ✅ stable list of states
texts.forEachIndexed { index, text ->
TextField(value = text, onValueChange = { texts[index] = it })
}
}
✔ Fix: Use mutableStateListOf for lists of states.
✅ In this batch we covered State Management best practices:
remember vs rememberSaveable
derivedStateOf for derived values
Avoiding passing raw MutableState
Stable keys in lists
State hoisting