mutableStateOf() tạo một MutableState<T> mà Compose theo dõi được: composable nào đọc .value sẽ được recompose khi giá trị đổi. remember giữ object đó qua các lần recomposition — thiếu remember, mỗi lần recompose lại tạo state mới về giá trị ban đầu.
@Composable
fun Counter() {
var count by remember { mutableStateOf(0) }
Button(onClick = { count++ }) { Text("Đã bấm $count lần") }
}Các biến thể cần biết:
- rememberSaveable: giữ giá trị qua xoay màn hình và process death (lưu vào Bundle); remember thì mất khi Activity bị tạo lại.
- mutableIntStateOf, mutableStateListOf, mutableStateMapOf: bản chuyên cho số và collection.
- State hoisting: đưa state lên cha, composable con chỉ nhận value + onValueChange → con stateless, dễ tái dùng và test.
State của cả màn hình (dữ liệu từ API) nên nằm trong ViewModel dưới dạng StateFlow, đọc bằng collectAsStateWithLifecycle().
Lưu ý: Compose chỉ biết khi bạn gán object mới vào state. mutableStateOf(mutableListOf<Item>()) rồi gọi list.add(x) sẽ không recompose — dùng mutableStateListOf() hoặc gán list mới (items = items + x).