remember vs rememberSaveable: choosing Compose state that survives the right events
A composable can be re-run at any moment, so any value that must outlive a single execution needs an explicit home. Jetpack Compose offers two: remember keeps a value in the composition's memory, while rememberSaveable adds a save-and-restore path through a Bundle. The difference is not cosmetic — it decides whether a dialog stays open after a rotation, and whether a counter resets when Android reclaims your process. This guide walks through the rendering phases, the State mechanism, the internals of both APIs, and a practical rule for choosing between them.
Why a composable cannot simply keep a variable
Compose builds a screen in three stages. Composition decides what to show by running your composable functions and producing a UI tree. Layout measures and positions each element in 2D space. Drawing paints the positioned elements onto a canvas, usually the device screen. The three stages form a one-way flow from description to pixels.
Recomposition restarts that flow at the composition stage whenever state changes. Because composable functions can be invoked again at any time, you should write them as if they will be. A local variable declared inside a composable is re-initialized on every execution, so it cannot carry a value forward on its own. Compose addresses this with State, which lets the runtime observe a value and re-run only the parts of the UI that depend on it.
A quick demonstration makes the failure obvious. A counter declared as a plain integer and incremented in a button's onClick never updates the label, because Compose has no way to observe the change. Switching to mutableStateOf gives the runtime something to observe, but the compiler flags it: creating a state object during composition without remember means the state is recreated each time the function runs. The value is observable but not retained.
What State actually buys you
State is the runtime's observation channel. When a state value changes, Compose re-runs the composable functions that read it and skips the parts of the tree that do not depend on it. That is why replacing a plain variable with a state-backed one makes the counter label update.
The remaining problem is lifetime. A state object created fresh on every recomposition is discarded and recreated along with the function call. remember solves this by asking the Composer to cache the value in memory and hand it back on subsequent executions. The cached value is kept until the composition leaves or until a supplied key changes, at which point remember invalidates and recreates it.
That is enough for values that only need to outlive recomposition. It is not enough for values that must outlive the composition itself.
The lifetime difference between remember and rememberSaveable
Both APIs cache values in the Compose runtime so a stateless function appears to hold onto data. Their behavior separates once the process or the composition is torn down.
remember keeps the value only while the process is alive. If Android kills the app process — for example, after backgrounding and reclaiming memory — the value is gone. rememberSaveable serializes the value into a Bundle, the standard Android instance-state mechanism, so it can be restored after configuration changes and process death.
A configuration change such as a rotation, a dark-mode switch or a system font-size adjustment recreates the activity. Values held only by remember are re-initialized; values held by rememberSaveable are restored from the Bundle. Process death is the harsher case: the whole process is gone, and only the saved Bundle survives.
Inside remember: a Composer cache with a key
The public shape of remember takes a key and a calculation lambda that is not allowed to call composables. It delegates to the current Composer, passing whether the key changed and the calculation. The Composer stores the result and returns the cached instance on later calls. When the key changes, the cache is invalidated and the calculation runs again.
The key is therefore the lever for resetting remembered state. Omit it and the value lives for the lifetime of that composition slot. Supply one and you control when the cache is thrown away.
Inside rememberSaveable: key, registry, holder, inputs
rememberSaveable is a small function wrapping a larger orchestration. Its parameters are the inputs vararg, a Saver that converts T into a bundle-compatible type, an optional key string, and an init lambda. The steps are:
- Determine a unique key. A developer-supplied key wins. Otherwise the current composite key hash — generated by the Compose compiler from the composable's position in the tree — is rendered in the maximum supported radix. This keeps state uniquely identified within its parent.
- Read the SaveableStateRegistry from a CompositionLocal. The registry is the authority that talks to the Android framework's saved instance state.
- Remember a SaveableHolder. On first creation the holder asks the registry whether a value was previously saved under the final key. If so, the Saver restores it to type T. If not, init produces the starting value.
- Return the holder's value if the inputs are unchanged, otherwise call init. A SideEffect then pushes the latest saver, registry, key, value and inputs into the holder after each successful recomposition.
The inputs behave like the keys of LaunchedEffect: when they change, the state is meant to reset. The holder exposes getValueIfInputsDidntChange, which returns null on a mismatch and signals rememberSaveable to re-initialize.
The SaveableHolder lifecycle
SaveableHolder is a private class that implements RememberObserver, which lets it hook into the composition lifecycle. Its responsibilities:
- Register on remember. When onRemembered fires, the holder registers with the SaveableStateRegistry. It does not hand over the value directly; it supplies a valueProvider lambda that runs the Saver when the registry asks for data during onSaveInstanceState. The registry returns an Entry handle.
- Unregister on forget. When the composable leaves the composition, or its rememberSaveable keys change, onForgotten calls entry?.unregister(). This stops the registry from saving state for disposed UI and avoids leaks.
- Stay synchronized on update. The update function, called from the SideEffect, refreshes the holder's value, saver and key. If the key or the registry itself changes, the holder unregisters and registers again so its registration stays valid.
- Detect input changes. getValueIfInputsDidntChange compares current inputs with the stored ones and returns null when they differ, which causes a reset to the init value.
The net effect is that persistence is tied to the composition lifecycle: state is offered for saving exactly while its composable is alive.
A checklist for choosing the right API
Ask what must survive, then pick the smallest mechanism that covers it.
- Does the value need to survive only recomposition within the current composition? Use remember with mutableStateOf.
- Must it survive a configuration change such as rotation, dark-mode toggle or font-size change? Use rememberSaveable.
- Must it survive system-initiated process death? Use rememberSaveable, and make sure the value's type is bundle-compatible or supply a Saver.
- Is the value expensive to recreate or non-serializable, such as a controller or a bitmap? remember is the better fit; rememberSaveable would add serialization overhead and may not be able to save the type at all.
- Is the value purely transient UI chrome, like a debug sheet's visibility? remember is usually enough, and resetting it on rotation is often acceptable.
- Is the value tied to entitlement or access control, like a paywall dialog that must not be dismissed by accident? rememberSaveable is the safer choice.
A common mistake is to reach for rememberSaveable everywhere because it is strictly more capable. It is not strictly better: it carries more overhead, and retaining state that should reset can itself cause bugs.
Worked example: a paywall dialog across a rotation
The upstream Android SDK this article draws on illustrates the split with two dialog patterns. In the first, a paywall dialog's visibility depends on whether the user is entitled to premium features. The composable reads shouldDisplayBlock from its options, initializes shouldDisplayDialog with rememberSaveable, and, when a block is present, launches a check that updates the flag.
If the user is not entitled, the dialog must remain visible. With rememberSaveable, a rotation or dark-mode switch restores the flag from the Bundle and the dialog stays up. With plain remember, the flag would be re-initialized to false on the same configuration change, and the user could slip past the paywall into premium features without an entitlement. The state is not decorative; it is part of access control.
In the second pattern, the same SDK's demo holds a debug bottom sheet, a login dialog and an API-key dialog with remember and mutableStateOf. On rotation those flags reset to false. That is acceptable because the user can reopen them, and keeping them out of the Bundle avoids unnecessary save/restore work.
The two cases look identical at the call site — a boolean that controls a dialog — but their consequences differ. The decision rule is about what happens if the value resets, not about what the value is.
Four failure modes and what each one means
- Plain variable: the UI never updates, because Compose cannot observe the change.
- mutableStateOf without remember: the compiler warns that a state object is being created during composition; the value is observable but recreated on each execution, so it does not persist.
- remember: the value survives recomposition but resets on configuration change and process death.
- rememberSaveable with mismatched inputs: the value is deliberately reset to init when the inputs change, which can look like data loss if the inputs were not intended as reset keys.
Each mode has a different fix. The first two need State plus remember. The third needs rememberSaveable if the value must outlive the composition. The fourth needs either stable inputs or a key that reflects the actual identity of the state.
rememberSaveable parameter map
- inputs (vararg Any?): reset keys. When any input changes between recompositions, the stored value is discarded and init runs again.
- saver (Saver<T, out Any>, default autoSaver()): converts T to a bundle-compatible representation and back. Supply one when the type is not handled automatically.
- key (String?, default null): the identifier used in the Bundle. When null, the composite key hash derived from the composable's position is used.
- init (() -> T): produces the starting value when nothing is restored and when inputs change.
A useful mental model: inputs answer "when should this reset?", key answers "where is this stored?", and saver answers "how is this encoded?".
| Mechanism | Survives recomposition | Survives configuration change | Survives process death | Typical cost |
|---|---|---|---|---|
| Plain local variable | No | No | No | None |
| mutableStateOf without remember | No (recreated each execution) | No | No | Compiler warning |
| remember { mutableStateOf(...) } | Yes | No | No | In-memory cache |
| rememberSaveable { mutableStateOf(...) } | Yes | Yes | Yes | Serialization into a Bundle |
Behavior described for the standard Compose runtime; custom Savers and registry configurations can change what is restorable.
Frequently asked questions
Why doesn't my counter update when I use a plain var?
Compose only recomposes when it observes a change through State. A plain local variable is invisible to the runtime, so incrementing it does not trigger a re-render. Wrap the value in mutableStateOf and hold it with remember so it is both observable and retained across recompositions.
Should I just use rememberSaveable everywhere?
No. rememberSaveable adds serialization and registry overhead, and retaining state that should reset can cause bugs of its own. Use it for values that must survive configuration changes or process death, and use remember for transient UI state that can safely reset.
Why did my rememberSaveable value reset even though nothing was killed?
The inputs vararg acts as a set of reset keys. If any input differs from the previous composition, getValueIfInputsDidntChange returns null and rememberSaveable falls back to init. Check that the inputs you pass are stable and actually identify the state.
When do I need to pass an explicit key to rememberSaveable?
When the default composite key hash is not unique enough for your situation — for example, when several instances of the same composable share a parent and must keep separate saved state. An explicit key makes the Bundle entry unambiguous.
What if my type cannot go into a Bundle?
Provide a Saver that converts your type into something bundle-compatible and back. If no reasonable conversion exists, the value probably belongs in remember rather than rememberSaveable, or in a ViewModel that outlives the composition.