pub fn retain_with_key<K, F, T>(key: K, init: F) -> State<T>Expand description
Retain a value across recomposition (build) passes with an explicit key, even if unused.
Unlike remember_with_key, 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 key is first
encountered. On subsequent updates with the same key, 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 remember_with_key
Use remember_with_key for ephemeral component state that should be
cleaned up when the component is no longer rendered. Use retain_with_key
for persistent state that must survive even when a subtree is not rebuilt
for some time.
§Panics
This function must be called during a component’s build/render phase. Calling it during the measure or input handling phases will panic.