mutableStateOf

Function

Common
@StateFactoryMarker
public fun <T> mutableStateOf(
    value: T,
    policy: SnapshotMutationPolicy<T> = structuralEqualityPolicy(),
): MutableState<T>

Return a new MutableState initialized with the passed in value

The MutableState class is a single value holder whose reads and writes are observed by Compose. Additionally, writes to it are transacted as part of the Snapshot system.

Parameters

valuethe initial value for the MutableState
policya policy to controls how changes are handled in mutable snapshots.

Code Examples

SimpleStateSample

@Composable
fun SimpleStateSample() {
    val count = remember { mutableStateOf(0) }
    Text(text = "You clicked ${count.value} times")
    Button(onClick = { count.value++ }) { Text("Click me") }
}

DestructuredStateSample

@Composable
fun DestructuredStateSample() {
    val (count, setCount) = remember { mutableStateOf(0) }
    Text(text = "You clicked $count times")
    Button(onClick = { setCount(count + 1) }) { Text("Click me") }
}

observeUserSample

@Suppress("unused")
fun observeUserSample() {
    @Composable
    fun observeUser(userId: Int): User? {
        val user = remember(userId) { mutableStateOf<User?>(null) }
        DisposableEffect(userId) {
            val subscription = UserAPI.subscribeToUser(userId) { user.value = it }
            onDispose { subscription.unsubscribe() }
        }
        return user.value
    }
}

stateSample

fun stateSample() {
    @Composable
    fun LoginScreen() {
        var username by remember { mutableStateOf("user") }
        var password by remember { mutableStateOf("pass") }
        fun login() = Api.login(username, password)
        BasicTextField(value = username, onValueChange = { username = it })
        BasicTextField(value = password, onValueChange = { password = it })
        Button(onClick = { login() }) { Text("Login") }
    }
}