retain

Function retain 

Source
pub fn retain<F, T>(init: F) -> State<T>
where F: FnOnce() -> T, T: Send + Sync + 'static,
Expand description

Retain a value across recomposition (build) passes, even if unused.

Unlike remember, state created with this function will not be recycled when the component stops calling it. This is useful for state that should persist across navigation, such as scroll positions or form inputs.

The init closure is executed only once — when the component first runs. On subsequent updates, the stored value is returned and init is not called.

§Use Cases

  • Preserving scroll position when navigating away and returning to a page
  • Retaining form input values across route changes
  • Caching expensive computation results that should survive component unmounts

§Interior mutability

This function returns a State<T> handle that internally uses an Arc<RwLock<T>>. Use with, with_mut, get, or set to read or update the value without handling synchronization primitives directly.

§Comparison with retain_with_key

retain identifies stored state based on the component’s call order and control-flow path. It associates state by position within a component, but this does not work reliably for dynamically generated state inside loops. For state that is allocated dynamically in loops, consider using retain_with_key to explicitly provide a unique key.

§Panics

This function must be called during a component’s build/render phase. Calling it during the measure or input handling phases will panic.