In Jetpack Compose, how do you hoist a checkout promo-code field's state so the field composable becomes stateless, and what does the caller gain?
answer
- state down, events up
- two parameters replace one var
- the current value plus a change callback
- lowest common parent of every reader
basics
~20 sMove the remembered value out of the field and replace it with two parameters: the current value and an onValueChange-style callback. The caller then owns the single source of truth, can share it with the price summary, and can intercept or reject each edit.
solid answer
~50 s**State hoisting** moves state from a composable to its caller. The field's internal `var code by remember { mutableStateOf("") }` becomes two parameters, `code: String` and `onCodeChange: (String) -> Unit`, and the `OutlinedTextField` inside simply shows `code` and forwards edits. State flows down, events flow up: **unidirectional data flow**. The caller now holds the single source of truth, so the price summary can read the same code; it can intercept each edit in the callback, uppercasing or capping the input before storing it; and the field can be previewed or reused with any value. Hoist to at least the lowest common parent of every composable that reads the state and the highest one that writes it, and hoist two states together when the same events change both. A useful pattern is to ship both a stateless version and a thin stateful wrapper.
code
kotlin · 26 lines@Composable
fun PromoCodeField(
code: String,
onCodeChange: (String) -> Unit,
modifier: Modifier = Modifier,
) {
OutlinedTextField(
value = code,
onValueChange = onCodeChange,
label = { Text("Promo code") },
singleLine = true,
modifier = modifier,
)
}
@Composable
fun CheckoutScreen() {
var promoCode by rememberSaveable { mutableStateOf("") }
Column {
PromoCodeField(
code = promoCode,
onCodeChange = { typed -> promoCode = typed.uppercase().take(12) },
)
Text("Promo: ${promoCode.ifEmpty { "none" }}")
}
}go deeper
Recall the shape: replace the remembered variable with a value parameter and an onValueChange callback, and let the caller hold the state.
Explain the three placement rules and the five properties hoisting buys, and show interception in the callback, such as uppercasing a promo code before storing it.
Spot under-hoisting in review: duplicated copies of one value, a MutableState parameter, or a screen-level holder passed into leaf composables, and refactor to values and events.
Make stateless-plus-stateful overloads the norm for shared components so a design system stays previewable and reusable, and decide how far up the tree screen state is allowed to travel.
## The stateful starting point A composable that calls `remember` to keep its own value is **stateful**. A promo-code field written that way works on its own, but nothing outside it can see or control what the user typed: - the price summary cannot show the discount for the code being entered; - the screen cannot clear the field after a successful apply; - a preview or a test cannot render it with a given value. In Jetpack Compose a text field does not update itself. `OutlinedTextField` displays its `value` parameter and reports edits through `onValueChange`; if nobody feeds the new value back, typing changes nothing on screen. ## The hoisted shape **State hoisting** replaces the state variable with two parameters: - `value: T`, the current value to display; - `onValueChange: (T) -> Unit`, an event that *requests* a change to the proposed new value. More specific event names are fine (`onCodeChange`, `onApply`). The field becomes **stateless**, and the caller decides where the value lives: ```kotlin @Composable fun PromoCodeField( code: String, onCodeChange: (String) -> Unit, modifier: Modifier = Modifier, ) { OutlinedTextField( value = code, onValueChange = onCodeChange, label = { Text("Promo code") }, singleLine = true, modifier = modifier, ) } ``` Name events after what happened rather than after a setter when that reads better: a field reports `onCodeChange`, while an Apply button reports `onApplyClick` and lets the owner decide what applying means. The stateless field can now be rendered with any fixed string, which is what makes previews and screenshot checks of each state cheap. The pattern where state goes down and events go up is **unidirectional data flow**. It separates the composables that display state from the code that stores and changes it. ## What the caller gains | Property | What it means on the checkout screen | |---|---| | Single source of truth | One `promoCode` value instead of a copy inside the field | | Encapsulated | Only the owner modifies it; the field can only ask | | Shareable | The price summary reads the same value | | Interceptable | The owner can normalise or reject each edit in the callback | | Decoupled | The value can live in the screen, a state holder or a screen-level holder without changing the field | ## Where to hoist: three rules 1. Hoist to at least the **lowest common parent** of all composables that read the state. 2. Hoist to at least the **highest level that writes** it. 3. If two states change in response to the **same events**, hoist them together. Hoisting higher than these rules require is allowed; **under-hoisting** is what breaks unidirectional data flow, because two composables end up holding their own copies. The flip side is to keep state as close as possible to where it is consumed: a flag that only one row reads, such as whether a breakdown is expanded, can stay internal to that row. ## Stateful and stateless versions together Reusable components often expose both. The stateless one takes value and events; a thin stateful wrapper calls `rememberSaveable` and delegates to it. Callers that do not care about the state use the wrapper; callers that need to read, share or intercept it use the stateless one. Compose's own lazy lists follow the same idea: they accept a state object as a parameter with a remembered default, so a caller can hoist it when it needs to. ## Pitfalls - **Passing `MutableState<String>` instead of value and callback.** The child can then write directly, the owner loses the chance to intercept, and the signature hides the fact that the child mutates shared state. - **Passing a screen-level state holder down.** A child that receives the whole holder can reach far more than it needs, and it can no longer be previewed or reused without that holder. Pass the values and lambdas it actually uses. - **Wrapping everything in one bundle class to shorten signatures.** Passing several values and lambdas down (property drilling) keeps each composable's responsibilities visible at a glance; a wrapper class hides them and tends to hand children parameters they do not need. - **Hoisting state that nobody else needs.** It is not wrong, but it widens what the caller must manage for no benefit.
- Why not pass a `MutableState<String>` into the field and let it write the value itself?Then two composables can write the same state, so the owner can no longer intercept, validate or ignore an edit, and the signature hides that the child mutates shared data. Value plus callback keeps the owner as the only writer and lets previews pass a fixed string.
- When is it fine to leave state inside a composable instead of hoisting it?When no other composable needs to read or control it and the logic is simple: an expand/collapse flag on a single row, or an animation's progress. That composable is then the owner and single source of truth, and hoisting would only add plumbing.
- The checkout screen ends up passing six values and five lambdas to its form. Should you bundle them into one class?Usually not. Passing individual values and lambdas, often called property drilling, keeps what each composable reads and triggers visible in its signature and pushes you to pass only what it uses. A wrapper class shortens the call but hides responsibilities and tends to leak extra state into children.
- A stateless field should take a MutableState so callers can share it
- Hoisting state means moving it to the top of the app
- OutlinedTextField keeps its own text, so hoisting is optional for input
- Hoisted state cannot be saved across rotation
- Two composables reading the same value should each remember a copy