How to Use mutableStateOf in Jetpack Compose for Android
In Jetpack Compose, use
mutableStateOf to create a state holder that triggers UI recomposition when its value changes. Declare it inside a composable or a ViewModel, then update its value to automatically refresh the UI.Syntax
The mutableStateOf function creates a mutable state object that holds a value and notifies Compose when the value changes. You typically declare it like this:
var state = mutableStateOf(initialValue): Holds the current value.- Use
state.valueto read or update the value. - When
state.valuechanges, Compose recomposes the UI that reads it.
kotlin
var count = mutableStateOf(0) // Read value val currentCount = count.value // Update value count.value = currentCount + 1
Example
This example shows a button that increments a counter using mutableStateOf. The UI updates automatically when the counter changes.
kotlin
import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.window.singleWindowApplication fun main() = singleWindowApplication { var count by remember { mutableStateOf(0) } Button(onClick = { count++ }) { Text("Clicked $count times") } }
Output
A window with a button labeled 'Clicked 0 times'. Each click updates the label to 'Clicked 1 times', 'Clicked 2 times', etc.
Common Pitfalls
Common mistakes when using mutableStateOf include:
- Not using
rememberinside composables, causing state to reset on recomposition. - Using
var state = mutableStateOf()without delegation, making code verbose. - Updating state outside the main thread, which can cause UI issues.
kotlin
/* Wrong: state resets on recomposition */ @Composable fun Counter() { var count = mutableStateOf(0) // recreated every recomposition Button(onClick = { count.value++ }) { Text("Count: ${count.value}") } } /* Right: use remember to keep state */ @Composable fun Counter() { var count by remember { mutableStateOf(0) } Button(onClick = { count++ }) { Text("Count: $count") } }
Quick Reference
| Concept | Usage | Notes |
|---|---|---|
| mutableStateOf | mutableStateOf(initialValue) | Creates observable state |
| Access value | state.value | Get or set current value |
| Remember state | remember { mutableStateOf(initialValue) } | Preserves state across recompositions |
| Property delegate | var x by mutableStateOf(initialValue) | Simplifies syntax with 'by' keyword |
| Update state | state.value = newValue | Triggers UI recomposition |
Key Takeaways
Use mutableStateOf to hold state that triggers UI updates in Compose.
Always use remember inside composables to keep state across recompositions.
Use property delegation (by) for cleaner and simpler state code.
Update state only on the main thread to avoid UI issues.
Reading or writing state.value automatically refreshes the UI.