Instruction 1

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Remember the central pantry for baking ingredients from the introduction? The central pantry is accessible to all steps (the child composables) that need to store ingredients there. The main recipe (the parent composable) controls the ingredients that go into each steps, such as the quantity of flour or butter.

State hoisting is the pattern of moving state to a composable caller, similar to storing the ingredients at the central pantry. This makes a composable stateless.

The general pattern of state hoisting is to replace the state variable with two parameters:

  • value: T: The current value to display. This represents any state that you can modify.
  • onValueChanged: (T) -> Unit: An event that updates the value, where T is the new value.

For example, take a look at the Greetings() composable that lets a user enter the name of the friend they’d like to send greetings to:

@Composable
fun Greetings(
  // 1
  friendName: String,
  // 2
  onNameChanged: (String) -> Unit,
  modifier: Modifier = Modifier
) {
  Column(
    modifier = modifier
  ) {
    Text(text = "Hello $friendName!")

    OutlinedTextField(
      value = friendName,
      // 3
      onValueChange = onNameChanged
    )
  }
}

In the Greetings() composable:

  1. friendName represents the value to display.
  2. onNameChanged lambda represents the event that updates the value stored in the friendName when the state needs updating.
  3. onNameChanged lambda is called when the user enters their friend’s name to update the value stored in the friendName state variable.

Then, you call the Greetings() composable in the GreetingsScreen() composable like this:

@Composable
fun GreetingsScreen() {
  // 1
  var friendName by remember { mutableStateOf("") }
  Greetings(
    friendName = friendName,
    onNameChanged = { newName ->
      friendName = newName
    }
  )
}

The code above:

  1. Creates the friendName state variable using the remember function.

A composable function that uses the remember function to store an object contains an internal state. A composable with an internal state is a stateful composable.

The GreetingsScreen composable is a stateful composable. It holds the friendName state and modifies it by calling the Greetings() composable.

Good Job! You learned about state hoisting. You’ll use this to create reusable composable functions in the Wellness Club app.

See forum comments
Download course materials from Github
Previous: Introduction Next: Demo