State hoisting
Why it matters
- A child that owns its own state is invisible to the parent; the parent cannot read, reset, or sync that value, which breaks forms, search screens, and multi-step flows.
- State hoisting makes a composable depend only on its parameters, so you can preview it and test it in a Compose UI test by passing fixed values, without clicking through to reach a state.
- Interviewers ask about 'state down, events up' to check whether you know who owns state and that recomposition follows where state is read, not where it is declared.
- Hoisting is the Compose equivalent of lifting state up in React; knowing the pattern by name helps you read other teams' code and discuss architecture in reviews.
The simple explanation
- A thermostat display shows the room temperature and has up/down buttons.
- The display does not own the temperature; the heating system does.
- The display is a stateless view: it renders whatever number the system gives it.
- When a user presses up, the display sends an event to the system, not the other way around.
- The system (parent) can also change the temperature from a phone app, a schedule, or a sensor.
- If the display kept its own copy, the phone app and the schedule could not reach it.
A stateful composable creates and keeps its own state with remember { mutableStateOf(...) }. A stateless (hoisted) composable receives the value as a parameter and reports changes through a callback lambda. The parent owns the state; the child never calls remember for that value.
The rule is state down, events up: the parent passes the current value down as a parameter; the child calls an onXChange lambda when the user interacts.
| Aspect | Stateful child | Hoisted (stateless) child |
|---|---|---|
| Who owns the state | The child | The parent (or a ViewModel) |
| Parameters | None or few | Value + callback |
| Parent can read or reset the value | No | Yes |
| Preview and UI test | Must click to reach a state | Pass any value directly |
| What re-runs on change | The child scope that reads it | The scopes that read it, often the parent; children with unchanged arguments are skipped |
The child must use the parameter it was given on every call. It must not copy the value into a local remember; the callback is the only channel back to the parent.
Where to hoist: to at least the lowest common parent of every composable that reads the state, and at least as high as the highest place that writes it. Two states that change in response to the same events should be hoisted together. When the state involves business logic or must outlive the screen's composition, hoist it into a ViewModel.
Typed state holders (mutableIntStateOf, mutableLongStateOf, mutableFloatStateOf, mutableDoubleStateOf) avoid boxing. The by delegate (var x by remember { mutableStateOf(0) }) reads and writes the underlying MutableState for you.
Notes
- State hoisting means the parent owns the state and passes the value down as a parameter; the child reports changes through a callback lambda.
- The child must not wrap the incoming value in its own
remember { mutableStateOf(...) }; that creates a second source of truth and the two copies drift. - State reads decide what re-runs: the scope that reads a
MutableStaterecomposes when it changes. Children whose arguments did not change are skipped. - Use typed state holders (
mutableIntStateOfand friends) forInt,Long,FloatandDoubleto avoid boxing. There is no special holder forBoolean; usemutableStateOf(false). - A hoisted composable is easy to test: in a Compose UI test, set it with a fixed value and a lambda, perform a click, and assert the lambda received the expected argument.
- Do not hoist truly local UI state, such as whether a dropdown menu is expanded, when no other composable needs it.
- Hoist to the lowest common parent of all readers. Hoisting higher adds readers and work for no benefit.
rememberloses its value on rotation and process death. If hoisted state must survive those, userememberSaveablein the parent orSavedStateHandlein a ViewModel.- The callback is conventionally named
onXChangeoronXClick. It is a() -> Unitor(T) -> Unitlambda, not aStateobject. - A ViewModel survives configuration changes but not process death on its own. Save the small, important values in
SavedStateHandle.
Code example
A search bar before and after hoisting: the stateful version hides the query inside the child, the hoisted version lets the parent own the string and react to it.
// --- Stateful: parent cannot read or reset the query ---
@Composable
fun StatefulSearchBar() {
var query by remember { mutableStateOf("") }
OutlinedTextField(
value = query,
onValueChange = { query = it },
label = { Text("Search") },
)
// query is invisible outside this function
}
// --- Hoisted: parent owns the state ---
@Composable
fun SearchBar(
query: String,
onQueryChange: (String) -> Unit,
modifier: Modifier = Modifier,
) {
OutlinedTextField(
value = query,
onValueChange = onQueryChange,
label = { Text("Search") },
modifier = modifier,
)
}
// Parent is the single source of truth
@Composable
fun SearchScreen() {
var query by rememberSaveable { mutableStateOf("") }
Column {
SearchBar(query = query, onQueryChange = { query = it })
// Parent can now filter, navigate, or reset freely
if (query.length > 2) {
Text("Results for: " + query)
}
Button(onClick = { query = "" }) { Text("Clear") }
}
}SearchBartakes aStringand a(String) -> Unit; it never callsrememberormutableStateOf, so what it shows depends only on its parameters.- The parent owns the state with
rememberSaveable, so the query also survives rotation. Thebydelegate reads and writes the underlyingMutableState. - The
if (query.length > 2)block shows why hoisting matters: the parent reacts to the value, which was impossible with the stateful version. onQueryChangeis passed straight toOutlinedTextField'sonValueChange; no extra copy of the text exists in the child.
Run the idea in plain Kotlin
Compose is not available here, but the ownership idea is plain Kotlin: one version hides its count inside an object, the other only renders what the owner gives it.
class StatefulCounter {
private var count: Int = 0
fun increment() { count++ }
fun display(): String = "Count: " + count
}
fun statelessCounter(count: Int): String = "Count: " + count
fun main() {
// Stateful: the count is private, so the owner cannot read or reset it
val s = StatefulCounter()
s.increment()
s.increment()
println("Stateful display: " + s.display())
// Hoisted: the owner holds the Int, the renderer only shows it
var parentCount = 0
val onIncrement: () -> Unit = { parentCount++ }
println("Before: " + statelessCounter(parentCount))
onIncrement()
onIncrement()
onIncrement()
println("After 3 clicks: " + statelessCounter(parentCount))
// The owner can reset or set the value from any source
parentCount = 0
println("Parent reset: " + statelessCounter(parentCount))
parentCount = 99
println("Parent set to 99: " + statelessCounter(parentCount))
// A pure renderer is easy to check: known input, known output
val result = statelessCounter(5)
println("Check (input=5): " + result + " -> " + (if (result == "Count: 5") "PASS" else "FAIL"))
}Expected output:
Stateful display: Count: 2
Before: Count: 0
After 3 clicks: Count: 3
Parent reset: Count: 0
Parent set to 99: Count: 99
Check (input=5): Count: 5 -> PASS
In production
- Users typed in the search bar but the results list below never updated.
- The search bar was a stateful composable that kept its own
remember { mutableStateOf("") }. - The results list read a different
queryvariable in the parent, which nobody ever wrote, so it stayed empty.
- Reproduced it in a preview: typing changed the field but not the results.
- Hoisted the query into the parent
SearchScreen;SearchBarnow takesquery: StringandonQueryChange: (String) -> Unit. - Added a Compose UI test that sets
SearchBarwith a fixed query, types into it, and asserts the callback receives the new text. - The results list and the search bar now read the same state, so they cannot disagree.
- A three-step onboarding form lost entered data when the user went back to an earlier step and forward again.
- Each step was its own navigation destination and held its fields in
remember { mutableStateOf(...) }. - Leaving a destination removes its composables from the composition, and
remembervalues are dropped with them. A step popped off the back stack loses even itsrememberSaveablestate.
- Moved the form into one
FormStatedata class held in aViewModelscoped to the onboarding navigation graph, exposed as aStateFlow. - Each step composable became stateless: it receives its slice of
FormStateand sends changes through callbacks. - Because the graph-scoped
ViewModeloutlives each step, going back and forward keeps the data. - Stored the current step and the entered values in
SavedStateHandleso they also come back after process death.
Common mistakes
- Copying the incoming parameter into another remember. The child creates a second copy that stops following the parent after the first composition. Use the parameter directly; for a calculated value, use a plain
valin the body (orremember(param)for expensive work). - Hoisting truly local UI state. Whether a dropdown is expanded usually matters only to that component. Hoisting it adds parameters and makes the parent a reader of state it does not need. Keep it local with
remember. - Passing only the value, forgetting the callback. The child can render but cannot report user input. A text field will look frozen because the parent's state never changes. Always pair a value with an
onXChangeoronXClicklambda. - Passing a whole state object when a child needs one field. The child then re-runs whenever any field changes. Pass only the fields it uses, so Compose can skip it when they are equal.
- Expecting remember to survive process death.
rememberis lost on rotation and process death. UserememberSaveablein the parent for small UI state, orSavedStateHandlein a ViewModel. Neither restores state after a crash or after the user swipes the app away. - Using a callback lambda as an effect key. A long-running
LaunchedEffectkeyed ononTimeoutrestarts whenever the parent passes a new lambda. Keep the effect's real keys and read the callback throughrememberUpdatedState(onTimeout)instead.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What is state hoisting in Compose and why do it?”
“How does state hoisting affect which composables recompose?”
“When should you NOT hoist state?”
“How would you structure a multi-field form with state hoisting?”
Quiz
What does state hoisting mean in Compose?
A child composable receives a query: String parameter but copies it into var local by remember { mutableStateOf(query) }. What happens?
Which state holder should a parent use for an Int counter that must survive system-initiated process death?
A parent reads one FormState data class and passes each field to its own field composable. The user types in the name field. What re-runs?
0 of 4 answered
Mini task
Hoist a counter into a parent (15 min)
-
Create a composable
CounterButton(label: String, count: Int, onIncrement: () -> Unit)that showsText("$label: $count")and aButton(onClick = onIncrement)with the label text. Do not callrememberormutableStateOfinside it. -
Create a
CounterScreen()composable. Inside it, declarevar count by remember { mutableIntStateOf(0) }. CallCounterButton(label = "Clicks", count = count, onIncrement = { count++ }). -
Below the button, add
Text("Total: $count")andButton(onClick = { count = 0 }) { Text("Reset") }. This proves the parent can read and reset the value. -
Add a second
CounterButton(label = "Alt", count = count, onIncrement = { count++ })to confirm both buttons share the same state. -
Run the app. Click each button a few times, then click Reset. Both counters should show 0.
-
Now try the anti-pattern: inside
CounterButton, addval localCount by remember { mutableIntStateOf(count) }and showlocalCountinstead ofcount. Run again. Observe that "Total" keeps counting while both buttons stay stuck on their first value.
Done condition: Both CounterButton instances show the same number, Reset sets both to 0, and you can explain why the anti-pattern stops the buttons from updating.