Skip to main content

mutableStateOf

Function mutableStateOf 

Source
pub fn mutableStateOf<T: Clone + 'static>(initial: T) -> MutableState<T>
Expand description

Creates a new MutableState initialized with the given value.

MutableState is a cheap copyable observable handle. Reads are tracked by the current composer or snapshot, and writes trigger recomposition of scopes that read it.

§When to use

Use mutableStateOf when:

  1. You are creating state properties inside a struct or class (not a composable function).
  2. You are implementing a custom state management solution.

If you are inside a #[composable] function, use useState instead. useState wraps mutableStateOf in remember, ensuring the state persists across recompositions. Using mutableStateOf directly in a composable will recreated the state on every frame, losing data.

§Example

struct MyViewModel {
    name: MutableState<String>,
}

impl MyViewModel {
    fn new() -> Self {
        Self {
            name: mutableStateOf("Alice".into()),
        }
    }
}

This creates a runtime-owned persistent state. If you need the state lifetime tied to a Rust owner instead, store an OwnedMutableState or call MutableState::retain on a handle returned by useState.