0
0
Android-kotlinHow-ToBeginner ยท 3 min read

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.value to read or update the value.
  • When state.value changes, 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 remember inside 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

ConceptUsageNotes
mutableStateOfmutableStateOf(initialValue)Creates observable state
Access valuestate.valueGet or set current value
Remember stateremember { mutableStateOf(initialValue) }Preserves state across recompositions
Property delegatevar x by mutableStateOf(initialValue)Simplifies syntax with 'by' keyword
Update statestate.value = newValueTriggers 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.