State Hoisting in Android Jetpack Compose

Jetpack Compose State Hoisting

In Jetpack Compose, state hoisting means moving the state of a composable to its parent (caller). It helps us to reuse the composables. Let us understand it with examples.

Prerequisites:

Let’s create a TextField().

@Composable
fun TextFieldExample() {
    // This is the state
    var name by remember { mutableStateOf("") }

    TextField(
        value = name,
        onValueChange = { name = it },
        label = { Text(text = "Enter Your Name") }
    )
}

In the above composable, we are storing the state using the name variable. We are keeping it in the TextFieldExample(). The problem with this approach is that we cannot reuse the TextFiled(). Also, it is difficult to test composables. So, let’s create a parent composable and move the state to it.

@Composable
fun UserDetails() {
    // This is the state
    var name by remember { mutableStateOf("") }

    TextFieldExample(
        name = name,
        onValueChange = { name = it },
        label = "Enter Your Name"
    )
}

@Composable
fun TextFieldExample(
    name: String,
    onValueChange: (String) -> Unit,
    label: String
) {
    TextField(
        value = name,
        onValueChange = onValueChange,
        label = { Text(text = label) }
    )
}

Now, our TextFieldExample() became stateless. It cannot change the state itself. The best thing about state hoisting is that we can call TextFieldExample() multiple times. For example, you can use it to get all the user’s details like email id, phone number, password, etc… You don’t need to create multiple TextFiled() composables.

Leave a Comment