Instruction

What is State?

State is any value in an app that can change over time—for example, your friend’s name from the previous section. A list of tasks in a TODO app is another example of state.

State is passed as a parameter to a composable function. Consider the following code:

@Composable
  fun Greeting(
    // 1
    friendsName: String,
    modifier: Modifier = Modifier
  ) {
    Text(
      // 2
      text = "Hello $friendsName!",
      modifier = modifier
    )
  }

The Greetings() composable function displays a greeting on the screen. You must provide it with the information it needs, like your friend’s name.

  1. Your friend’s name is stored in the state variable friendsName, which is passed as a parameter to the Greetings() composable.

  2. The Text() composable displays the greeting using the value of friendsName passed to the parent composable.

When you call the Greetings() composable, you pass a value for your friend’s name, like Bob.

Greeting(friendsName = "Bob")

Recomposition

You’ve sent the greetings to Bob. Now, you want to send greetings to Sally. All you have to do is call the Greetings() composable with a new value for the state variable, friendsName.

Greeting(friendsName = "Sally")

In Jetpack Compose, when you need to update the UI you call the same composable with new arguments.

Imagine your UI is like a recipe in Jetpack Compose. When an ingredient (state) changes, you don’t have to rewrite the entire recipe( the composable function). Instead, you simply provide the new ingredient (state). Then Compose automatically cooks up a fresh UI based on the updated recipe.

This process of recreating the UI based on new values is called recomposition.

Now you know what state is in an Android app. In the next section, you’ll build a Wellness Club app and learn more about the state in a hands-on demonstration.

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