Instruction 2

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

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

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

Unlock now

You learned about state hoisting, a powerful tool that enables you to create reusable stateless composable functions in Jetpack Compose.

With great power comes great responsibility! Here are some things you should keep in mind when implementing state hoisting.

Hoist to the Lowest Common Ancestor

The state should be hoisted to the lowest common parent of all the composables that use that state. As you write composables for your app UI, identify state variables multiple composables use. Lift the state variable to the closest parent composable that all those children share, the lowest common ancestor.

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

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

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

Unlock now
@Composable
fun DisplayItem(itemValue: String, isEditing: Boolean) {
  if (isEditing) {
    TextField(value = itemValue, onValueChange = {})
  } else {
    Text(text = itemValue)
  }
}

@Composable
fun EditButton(isEditing: Boolean, onEditingChanged: (Boolean) -> Unit) {
  Button(onClick = {
    onEditingChanged(!isEditing)
  }) {
    Text(text = if (isEditing) "Done" else "Edit")
  }
}
@Composable
fun ProfileContent(userData: UserData) {
  var isEditing by remember { mutableStateOf(false) }

  DisplayItem(itemValue = userData.name, isEditing = isEditing)

  DisplayItem(itemValue = userData.email, isEditing = isEditing)

  EditButton(isEditing = isEditing, onEditingChanged = {
    isEditing = !isEditing
  })
}
@Composable
fun ProfileScreen(){
  val userProfile by remember { mutableStateOf(UserData()) }
  ProfileContent(userData = userProfile)
}

@Composable
fun ProfileContent(userData: UserData) {
  var isEditing by remember { mutableStateOf(false) }

  DisplayItem(itemValue = userData.name, isEditing = isEditing)

  DisplayItem(itemValue = userData.email, isEditing = isEditing)

  EditButton(isEditing = isEditing, onEditingChanged = {
    isEditing = !isEditing
  })
}
See forum comments
Download course materials from Github
Previous: Demo Next: Conclusion