State hoisting

Learn state hoisting in Jetpack Compose to lift state from child composables to parents, enabling better testing, control, and architectural patterns. About 20 minutes.

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.

AspectStateful childHoisted (stateless) child
Who owns the stateThe childThe parent (or a ViewModel)
ParametersNone or fewValue + callback
Parent can read or reset the valueNoYes
Preview and UI testMust click to reach a statePass any value directly
What re-runs on changeThe child scope that reads itThe 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.

State down, events up
State down, events up The stateful parent passes the temperature down to the stateless child as a parameter, and the child draws it. When the user taps a button, the child calls the onXChange lambda. The parent updates its state and passes the new value down again. State flows down, events flow up temperature DRAWS THE VALUE TAPS UP OR DOWN onValueChange(new) UPDATES ITS STATE NEW temperature Stateful parent owns the state Stateless child draws parameters User taps a button
The child never keeps its own copy: it draws the value it is given and reports changes through the lambda.

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 MutableState recomposes when it changes. Children whose arguments did not change are skipped.
  • Use typed state holders (mutableIntStateOf and friends) for Int, Long, Float and Double to avoid boxing. There is no special holder for Boolean; use mutableStateOf(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.
  • remember loses its value on rotation and process death. If hoisted state must survive those, use rememberSaveable in the parent or SavedStateHandle in a ViewModel.
  • The callback is conventionally named onXChange or onXClick. It is a () -> Unit or (T) -> Unit lambda, not a State object.
  • 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") }
    }
}
  • SearchBar takes a String and a (String) -> Unit; it never calls remember or mutableStateOf, so what it shows depends only on its parameters.
  • The parent owns the state with rememberSaveable, so the query also survives rotation. The by delegate reads and writes the underlying MutableState.
  • The if (query.length > 2) block shows why hoisting matters: the parent reacts to the value, which was impossible with the stateful version.
  • onQueryChange is passed straight to OutlinedTextField's onValueChange; 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

Search screen that never filtered
  • 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 query variable in the parent, which nobody ever wrote, so it stayed empty.
The fix
  • Reproduced it in a preview: typing changed the field but not the results.
  • Hoisted the query into the parent SearchScreen; SearchBar now takes query: String and onQueryChange: (String) -> Unit.
  • Added a Compose UI test that sets SearchBar with 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.
Multi-step form that lost data on back navigation
  • 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 remember values are dropped with them. A step popped off the back stack loses even its rememberSaveable state.
The fix
  • Moved the form into one FormState data class held in a ViewModel scoped to the onboarding navigation graph, exposed as a StateFlow.
  • Each step composable became stateless: it receives its slice of FormState and sends changes through callbacks.
  • Because the graph-scoped ViewModel outlives each step, going back and forward keeps the data.
  • Stored the current step and the entered values in SavedStateHandle so 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 val in the body (or remember(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 onXChange or onXClick lambda.
  • 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. remember is lost on rotation and process death. Use rememberSaveable in the parent for small UI state, or SavedStateHandle in 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 LaunchedEffect keyed on onTimeout restarts whenever the parent passes a new lambda. Keep the effect's real keys and read the callback through rememberUpdatedState(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)

  1. Create a composable CounterButton(label: String, count: Int, onIncrement: () -> Unit) that shows Text("$label: $count") and a Button(onClick = onIncrement) with the label text. Do not call remember or mutableStateOf inside it.

  2. Create a CounterScreen() composable. Inside it, declare var count by remember { mutableIntStateOf(0) }. Call CounterButton(label = "Clicks", count = count, onIncrement = { count++ }).

  3. Below the button, add Text("Total: $count") and Button(onClick = { count = 0 }) { Text("Reset") }. This proves the parent can read and reset the value.

  4. Add a second CounterButton(label = "Alt", count = count, onIncrement = { count++ }) to confirm both buttons share the same state.

  5. Run the app. Click each button a few times, then click Reset. Both counters should show 0.

  6. Now try the anti-pattern: inside CounterButton, add val localCount by remember { mutableIntStateOf(count) } and show localCount instead of count. 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.

Next: Lists with LazyColumn