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 an observable value holder. 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()),
        }
    }
}