skip to content

As the Android lead on a Jetpack Compose codebase, what rule would you set for where UI state lives: in composables, plain state holder classes or screen-level state holders?

level: principalimportance: should knowfreq 40%

answer

  1. UI element state versus screen UI state
  2. UI logic versus business logic
  3. rememberSomethingState factories
  4. lowest common ancestor, not the top
  5. values and lambdas go down

basics

~20 s

Keep simple UI element state in the composable that uses it, hoisted only to the lowest common ancestor; put complex UI logic in a remembered plain state holder; keep screen UI state and business logic in a screen-level holder, passing values and lambdas down.

solid answer

~50 s

I would write the rule around two distinctions: **UI element state** versus **screen UI state**, and **UI logic** versus **business logic**. Element state with simple logic, such as an expanded flag or a typed promo code, stays in the composable with `remember` or `rememberSaveable`, hoisted to the lowest common ancestor of its readers and writers. When several element states share UI logic, they move into a **plain state holder class** created by a `rememberCheckoutFormState()` factory, the way `rememberLazyListState()` works, with a `Saver` so it survives recreation. Screen UI state built from other layers, and the business logic behind it, lives in a **screen-level holder** outside the Composition (in practice a `ViewModel`), collected once at the screen composable with `collectAsStateWithLifecycle`. Children receive plain values and event lambdas, never the holder or a `MutableState`. The judgment calls are how much to hoist and when a local piece of state has earned a holder.

code

kotlin · 29 lines
kotlin
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.Saver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue

@Stable
class CheckoutFormState(initialPromo: String) {
    var promoCode by mutableStateOf(initialPromo)
        private set
    val canApply: Boolean get() = promoCode.length >= 6

    fun onPromoChange(typed: String) {
        promoCode = typed.uppercase().take(12)
    }

    companion object {
        val Saver: Saver<CheckoutFormState, String> = Saver(
            save = { it.promoCode },
            restore = { CheckoutFormState(it) },
        )
    }
}

@Composable
fun rememberCheckoutFormState(): CheckoutFormState =
    rememberSaveable(saver = CheckoutFormState.Saver) { CheckoutFormState("") }

go deeper

for a junior

Recall the three places state can live in a Compose screen and the one-line test for each: who reads it, who writes it, and whether business logic is involved.

for a middle

Explain the difference between UI element state and screen UI state, and show a plain state holder with a remember factory and a Saver.

for a senior

Refactor a screen that drifted: pull duplicated state to the lowest common ancestor, extract a state holder, and stop passing the screen-level holder into leaves.

for a principal

Own the rule and its exceptions: weigh over-hoisting against under-hoisting, the saved-state budget and testability, and make the conventions enforceable through lint and review.

## Why this needs a team rule Compose lets state live almost anywhere: a `remember` in a leaf, a class remembered in a parent, or an object outside the Composition. Without a rule, a codebase drifts to both extremes. Some screens push every scroll position and expanded flag through the screen-level holder; others duplicate the same value in three composables. Both produce the same bug reports: state that resets, state that disagrees with itself, and components nobody can preview. ## The three owners | Owner | Lives as long as | Survives recreation by | Typical contents | |---|---|---|---| | The composable | its place in the Composition | `rememberSaveable` | expand flags, field text, animation state | | A plain state holder class | the composable that remembers it | a `Saver` in its `remember` factory | several element states plus the UI logic over them | | A screen-level holder | outside the Composition, scoped by the framework | its own saved-state mechanism | screen UI state, access to business logic | The split follows the kind of logic. **UI logic** (which hint to show, scrolling to an item, enabling a button) can stay in the UI. **Business logic** (applying a promo code against the server's rules, computing the order total) belongs to the layers behind the screen, reached through the screen-level holder. ## The default rules I would write down 1. Start local. State that one composable reads and writes stays there. 2. Hoist to the **lowest common ancestor** of all readers and the highest writer, and no further without a reason. 3. When a composable juggles several element states and the logic over them, extract a **plain state holder class** with a `rememberXState()` factory; reusable components take it as a parameter with that factory as the default. 4. Data that comes from other layers lives in the **screen-level holder** and is collected once, at the screen composable, with `collectAsStateWithLifecycle`. 5. Pass **values and event lambdas** down. Never pass the screen-level holder into children, and never take a `MutableState` parameter. 6. Prefer several explicit parameters (property drilling) over a wrapper class that bundles state and events, so each signature shows what the composable uses. ## What a plain state holder looks like ```kotlin @Stable class CheckoutFormState(initialPromo: String) { var promoCode by mutableStateOf(initialPromo) private set val canApply: Boolean get() = promoCode.length >= 6 fun onPromoChange(typed: String) { promoCode = typed.uppercase().take(12) } companion object { val Saver: Saver<CheckoutFormState, String> = Saver( save = { it.promoCode }, restore = { CheckoutFormState(it) }, ) } } @Composable fun rememberCheckoutFormState(): CheckoutFormState = rememberSaveable(saver = CheckoutFormState.Saver) { CheckoutFormState("") } ``` The class holds snapshot state, so reads in composition are tracked; the `@Stable` annotation is a promise used by the skipping rules covered with composable functions. Callers use `val formState = rememberCheckoutFormState()` and pass `formState.promoCode` and `formState::onPromoChange` to the stateless field. The holder owns UI logic only; checking the code against the order is business logic and stays with the screen-level holder. ## Trade-offs a lead weighs - **Over-hoisting.** Routing every keystroke and scroll offset through the screen-level holder makes it large, couples it to visual details, and keeps transient state alive after the UI that needed it is gone. - **Under-hoisting.** Copies of one value in two composables disagree, and features that need to read the state cannot reach it. - **Saved-state budget.** Element state saved with `rememberSaveable` shares a size-limited `Bundle`; the rule should say to save IDs and input, not data. - **Testability and previews.** Stateless composables with values and lambdas preview with fixed data; a component that requires the screen holder cannot. - **Portability.** A plain state holder built only on Compose runtime types can avoid Android framework dependencies, so its UI logic can be unit-tested without a device and reused across modules. ## Enforcing it - Review checklist items: no `MutableState` parameters, no screen-level holder below the screen composable, one lifecycle-aware collection per screen. - Raise Compose lint checks such as `UnrememberedMutableState` and `MutableCollectionMutableState` to errors in CI. - Require a stateless overload for every component in the shared UI module, with a thin stateful wrapper where it helps callers. - Revisit the rule when a feature does not fit it, rather than letting exceptions accumulate silently.

  • When should a plain state holder class give way to a screen-level holder?
    When the state depends on business logic or data from other layers, when it must outlive the composable that remembers it, or when it is screen UI state rather than element state. A promo field's text stays in the plain holder; whether the code is valid for this order comes from the screen-level holder.
  • Why forbid passing the screen-level holder into child composables?
    The child can then reach far more than it needs, its signature no longer shows what it reads or triggers, and it cannot be previewed or reused without that holder. Passing values and lambdas keeps children stateless and the screen the only place that knows where state comes from.
  • What does pushing every field and flag into the screen-level holder cost?
    The holder grows into a mirror of the layout, keeps transient visual state alive longer than the UI that used it, and needs its own saving for each field. Element state with only UI logic is cheaper and clearer next to the UI, saved with `rememberSaveable` where it matters.

  • All state, including scroll positions and expand flags, belongs in the screen-level holder
  • A plain state holder class survives process death on its own
  • Passing the screen-level holder down is fine because it avoids property drilling
  • Hoisting state as high as possible is always the safer default
  • Reusable components should accept MutableState so callers can share it