Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 104 ยท State in Compose

State Hoisting and Unidirectional Data Flow

Learn state hoisting in Compose: stateless composables, the value plus onValueChange pattern, a single source of truth and unidirectional data flow.

In State and remember you made a composable remember a value with remember { mutableStateOf(...) }. That works, but if every composable owns its own state, the screen becomes hard to test, hard to preview and hard to keep consistent. Two widgets that should show the same number end up with two different numbers.

The fix is a pattern called state hoisting: move the state out of a composable and into its caller, and let the composable receive the value and report changes through a callback. Combined with the rule that data flows down and events flow up, you get unidirectional data flow, the idea that Compose screens are built around. The real code needs the Android SDK, so the Compose snippets here are read-only. The runnable TryIt blocks are plain Kotlin stand-ins that model the pattern with functions and data, and each one says what it models.

Stateful and stateless composables

A stateful composable creates and owns some state. A stateless composable owns none: everything it shows arrives as a parameter, and everything the user does leaves as a callback.

Here is a stateful counter, the way you might first write it:

Kotlin
// read-only example: needs Compose
@Composable
fun CounterStateful() {
    var count by remember { mutableIntStateOf(0) }
    Button(onClick = { count++ }) {
        Text("Clicked $count times")
    }
}

It is easy to write, but you cannot show it with the count at 5 in a preview, you cannot test what it does at 99 without clicking 99 times, and no other composable can read the count.

Hoisting splits it in two:

Kotlin
// read-only example: needs Compose
@Composable
fun CounterScreen() {
    var count by rememberSaveable { mutableIntStateOf(0) }
    Counter(count = count, onIncrement = { count++ })
}

@Composable
fun Counter(count: Int, onIncrement: () -> Unit) {
    Button(onClick = onIncrement) {
        Text("Clicked $count times")
    }
}

Counter is now a pure description: given a number and a callback it draws a button. CounterScreen owns the state and decides what an increment means. The names follow a convention you will meet everywhere: a read-only value is called x or value, and the event that asks for a change is onXChange or onSomethingHappened.

The next TryIt models this split. A ButtonNode is a stand-in for a button on screen: a label plus a click handler. The stateful version hides the count inside; the stateless version only formats what it is given. Notice that the stateless one can be called with any number without any clicking.

Kotlin Stateful vs stateless counter (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Only the last section changed: because the caller holds count, it can read it at the end. That is what the stateful version cannot offer.

Single source of truth

When two parts of the UI need the same data, there must be exactly one place that owns it. Hoist the state to the lowest common parent of every composable that reads or writes it, and pass it down. Then there is no way for the two views to disagree, because there is only one value.

Kotlin
// read-only example: needs Compose
@Composable
fun TemperatureScreen() {
    var celsius by rememberSaveable { mutableStateOf("20") }
    Column {
        TemperatureField(value = celsius, onValueChange = { celsius = it })
        Text("In Fahrenheit: ${toFahrenheit(celsius)}")
    }
}

The text field edits the value and the Text displays something computed from it. Neither one stores a copy. If you caught yourself writing a second remember in Text to hold "the converted value", that second copy is the bug waiting to happen.

How high should the state go? A practical rule has three parts:

  • Hoist at least to the lowest common parent of all composables that read it.
  • Hoist at least to the highest level where it might be changed.
  • If two states change together in response to the same event, hoist them to the same place (or group them in one class).

You do not have to hoist everything to the top of the app. Purely visual state that nothing else cares about, like whether a dropdown is expanded or a tooltip is showing, can stay inside the composable that draws it.

Unidirectional data flow

Hoisting gives the UI a direction. State flows down from owners to children as parameters. Events flow up from children to owners as callbacks. The owner updates the state, Compose recomposes the affected parts, and the new state flows down again.

flowchart TD
    S["State owner<br/>(holds the value)"] -->|"state down"| U["Stateless UI<br/>(draws the value)"]
    U -->|"event up<br/>(onValueChange)"| S

State goes down as parameters; events come back up as callbacks, and only the owner changes the state.

This loop has useful properties. There is a single place where a given piece of state changes, so bugs are easy to find. The UI can never change state by itself, so you can intercept or reject a change. And a stateless composable is trivial to preview and test because you only need to hand it a value.

The interception point matters more than it first seems. A text field that receives value and onValueChange does not actually edit anything: it reports what the user typed, and the owner decides whether to accept it. If the owner ignores the callback, the text on screen does not change at all. That is the correct behavior, not a bug, and it means the owner can filter input.

Kotlin
// read-only example: needs Compose
@Composable
fun DigitsOnlyField() {
    var text by rememberSaveable { mutableStateOf("") }
    OutlinedTextField(
        value = text,
        onValueChange = { new -> if (new.all { it.isDigit() }) text = new },
        label = { Text("PIN") }
    )
}

The TryIt below is a stand-in for that loop. Owner holds the state, render is the stateless part, and onValueChange is the event handler. Typing a letter is reported upward but rejected by the owner, so the displayed text stays the same.

Kotlin State down, events up (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Real Compose does not call render by hand: it recomposes automatically when a mutableStateOf value that was read during composition changes. The shape of the loop is the same.

Hoisting to a state holder

As a screen grows, you will have several related values and some logic about them. Passing ten parameters around gets noisy. When the state and its rules belong together, group them in a state holder: a plain Kotlin class that owns the state and exposes functions to change it.

Kotlin
// read-only example: needs Compose
class SignUpState {
    var email by mutableStateOf("")
        private set
    var agreed by mutableStateOf(false)
        private set

    val canSubmit: Boolean
        get() = email.contains("@") && agreed

    fun onEmailChange(value: String) { email = value }
    fun onAgreedChange(value: Boolean) { agreed = value }
}

The private set makes the unidirectional rule enforceable: callers can read the state, but they can only change it through the functions you provide. For state that must survive configuration changes and hold business logic, the next level up is a ViewModel, which ViewModel covers later. The idea is identical: the UI receives state and sends events.

Designing good stateless composables

A few habits make hoisted composables pleasant to use:

  • Take only what you need. Accept a String, not an entire User object, if only the name is shown. Narrow parameters make recomposition cheaper and previews simpler.
  • Always accept a modifier. Put modifier: Modifier = Modifier as the first optional parameter so callers can control size and position.
  • Name callbacks as events. onClick, onValueChange and onDismiss describe what happened, not what to do about it.
  • Provide defaults for rarely changed parameters, but not for the state itself. The state parameter should be required, so nobody forgets to hoist it.
  • Preview with fixed values. A stateless composable plus @Preview is a one-line way to check any state: Counter(count = 99, onIncrement = {}).

Library components follow the same idea. TextField(value, onValueChange) is stateless, so you own the text. LazyColumn(state = rememberLazyListState()) takes an optional state object with a sensible default: pass your own when other code needs to read or control the scroll position, and leave it out otherwise.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What makes a composable stateless?

    A stateless composable owns no state. The value comes in as a parameter, changes go out through lambdas, and the caller decides what happens.
  2. 2. In unidirectional data flow, which way do state and events travel?

    Owners pass state down to children as parameters, and children send events up through callbacks. The owner updates the state and the UI is recomposed.
  3. 3. A TextField is given value = text and an onValueChange that does nothing. What does the user see when they type?

    The field only shows the value it is given. Typing triggers onValueChange, and if the owner ignores it the state is unchanged, so nothing new is displayed. This is how owners can reject input.
  4. 4. Where should state be hoisted when two sibling composables both read it?

    The lowest common parent of everything that reads the state is the smallest scope that gives a single source of truth without exposing the state more widely than needed.

Summary

  • Hoisting means moving state out of a composable and passing it in as a value plus an event callback (value and onValueChange).
  • Stateless composables are easy to preview, test and reuse; stateful ones are convenient but closed.
  • Keep one source of truth: hoist state to the lowest common parent of all readers.
  • State flows down as parameters, events flow up as callbacks, and only the owner changes the state.
  • Group related state and its rules in a state holder class, and use private set to enforce the direction.
  • Take narrow parameters, accept a modifier, and preview stateless composables with fixed values.
  • The Compose code here is read-only; the TryIt blocks are Kotlin stand-ins for the pattern.

Next: Recomposition and Stability