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:
onNameChanged lambda represents the event that updates the value stored in the friendName when the state needs updating.
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:
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
This content was released on Sep 10 2024. The official support period is 6-months
from this date.
In this lesson, you’ll learn about state hoisting and best practices for state hoisting in Jetpack Compose.
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.