Skip to content
DeveloperMemos

Hoisting State in Jetpack Compose

Jetpack Compose, Hoisting State, Android Development1 min read

Jetpack Compose, the modern toolkit for building native Android UI, brings a paradigm shift from the traditional View system. One of the key concepts introduced by Compose is managing and sharing state through 'Hoisting State'. In this article, we will deep-dive into this concept and explore how it benefits the composition of your UI components.

What is Hoisting State?

In Jetpack Compose, 'Hoisting State' refers to the practice of declaring a state at a higher level in the hierarchy and then passing it down to lower-level composable functions. The main idea is to move the state and the functions manipulating the state as high up in the composable hierarchy as it makes sense.

Hoisting State promotes better reusability and testability of your composable functions. It is also a way to avoid common pitfalls of managing state, such as uncontrolled state mutation.

Example of Hoisting State

Let's take a simple example where we have a Checkbox composable that we want to reuse in multiple places. The state of the Checkbox (whether it's checked or not) is a perfect candidate for hoisting.

1@Composable
2fun MyCheckbox(checked: Boolean, onCheckedChange: (Boolean) -> Unit) {
3 Checkbox(checked = checked, onCheckedChange = onCheckedChange)
4}
5
6@Composable
7fun ParentComposable() {
8 var checked by remember { mutableStateOf(false) }
9
10 MyCheckbox(checked = checked) { newChecked ->
11 checked = newChecked
12 }
13}

In this example, the ParentComposable is the one managing the state of the MyCheckbox. The state and its mutating function are passed down as parameters, effectively hoisting the state to the parent level.

Benefits of Hoisting State

Hoisting State comes with several benefits:

  1. Reusability: By decoupling the state from the composable, you can reuse it in different parts of your UI hierarchy without managing separate instances of state.

  2. Testability: Hoisted state makes testing easier. You can test your composable functions in isolation by providing mock state and functions.

  3. Debugging: Debugging is simpler as you can trace the state changes to a specific part of your hierarchy.

  4. Interoperability: Hoisting state aids in interoperability with other Jetpack Compose concepts like effects and modifiers.

Conclusion

State Hoisting is a powerful technique that makes your Composable functions more reusable, testable, and maintainable. Embracing it will lead to a more predictable and easier-to-debug application. Don't hesitate to hoist your state and make the most out of Jetpack Compose!