Skip to main content

rememberUpdatedState

Function rememberUpdatedState 

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

Returns a MutableState that always holds the latest value.

The state reference is stable across recompositions; only the value updates. This allows closures to capture a stable reference while reading fresh values.

§Use Case

Use when a remembered closure needs to read a value that changes each recomposition without recreating the closure itself.

§Example

let config = build_config(); // Rebuilt each recomposition
let config_state = rememberUpdatedState(config);

// This closure is created once, reads latest config via state
let callback = remember(|| {
    let cfg = config_state.clone();
    Rc::new(move || do_something(&cfg.value()))
}).with(|c| c.clone());

§JC Equivalent

@Composable
fun <T> rememberUpdatedState(newValue: T): State<T> =
    remember { mutableStateOf(newValue) }.apply { value = newValue }