State and Jetpack Compose

State in an app is any value that can change over time. This is a very broad definition and encompasses everything from a Room database to a variable on a class.

All Android apps display state to the user. A few examples of state in Android apps:

  • A Snackbar that shows when a network connection can't be established.
  • A blog post and associated comments.
  • Ripple animations on buttons that play when a user clicks them.
  • Stickers that a user can draw on top of an image.

Jetpack Compose helps you be explicit about where and how you store and use state in an Android app. This guide focuses on the connection between state and composables, and on the APIs that Jetpack Compose offers to work with state more easily.

State and composition

Compose is declarative and as such the only way to update it is by calling the same composable with new arguments. These arguments are representations of the UI state. Any time a state is updated a recomposition takes place. As a result, things like TextField don’t automatically update like they do in imperative XML based views. A composable has to explicitly be told the new state in order for it to update accordingly.

@Composable
fun HelloContent() {
   Column(modifier = Modifier.padding(16.dp)) {
       Text(
           text = "Hello!",
           modifier = Modifier.padding(bottom = 8.dp),
           style = MaterialTheme.typography.h5
       )
       OutlinedTextField(
           value = "",
           onValueChange = { },
           label = { Text("Name") }
       )
   }
}

If you run this, you'll see that nothing happens. That's because the TextField doesn't update itself—it updates when its value parameter changes. This is due to how composition and recomposition work in Compose.

To learn more about initial composition and recomposition, see Thinking in Compose.

State in composables

Composable functions can store a single object in memory by using the remember composable. A value computed by remember is stored in the Composition during initial composition, and the stored value is returned during recomposition. remember can be used to store both mutable and immutable objects.

mutableStateOf creates an observable MutableState<T>, which is an observable type integrated with the compose runtime.

interface MutableState<T> : State<T> {
    override var value: T
}

Any changes to value will schedule recomposition of any composable functions that read value. In the case of ExpandingCard, whenever expanded changes, it causes ExpandingCard to be recomposed.

There are three ways to declare a MutableState object in a composable:

  • val mutableState = remember { mutableStateOf(default) }
  • var value by remember { mutableStateOf(default) }
  • val (value, setValue) = remember { mutableStateOf(default) }

These declarations are equivalent, and are provided as syntax sugar for different uses of state. You should pick the one that produces the easiest-to-read code in the composable you're writing.

The by delegate syntax requires the following imports:

import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue

You can use the remembered value as a parameter for other composables or even as logic in statements to change which composables are displayed. For example, if you don't want to display the greeting if the name is empty, use the state in an if statement:

@Composable
fun HelloContent() {
   Column(modifier = Modifier.padding(16.dp)) {
       var name by remember { mutableStateOf("") }
       if (name.isNotEmpty()) {
           Text(
               text = "Hello, $name!",
               modifier = Modifier.padding(bottom = 8.dp),
               style = MaterialTheme.typography.h5
           )
       }
       OutlinedTextField(
           value = name,
           onValueChange = { name = it },
           label = { Text("Name") }
       )
   }
}

While remember helps you retain state across recompositions, the state is not retained across configuration changes. For this, you must use rememberSaveable. rememberSaveable automatically saves any value that can be saved in a Bundle. For other values, you can pass in a custom saver object.

Other supported types of state

Jetpack Compose doesn't require that you use MutableState<T> to hold state. Jetpack Compose supports other observable types. Before reading another observable type in Jetpack Compose, you must convert it to a State<T> so that Jetpack Compose can automatically recompose when the state changes.

Compose ships with functions to create State<T> from common observable types used in Android apps:

You can build an extension function for Jetpack Compose to read other observable types if your app uses a custom observable class. See the implementation of the builtins for examples of how to do this. Any object that allows Jetpack Compose to subscribe to every change can be converted to State<T> and read by a composable.

Stateful versus stateless

A composable that uses remember to store an object creates internal state, making the composable stateful. HelloContent is an example of a stateful composable because it holds and modifies its name state internally. This can be useful in situations where a caller doesn't need to control the state and can use it without having to manage the state themselves. However, composables with internal state tend to be less reusable and harder to test.

A stateless composable is a composable that doesn't hold any state. An easy way to achieve stateless is by using state hoisting.

As you develop reusable composables, you often want to expose both a stateful and a stateless version of the same composable. The stateful version is convenient for callers that don't care about the state, and the stateless version is necessary for callers that need to control or hoist the state.

State hoisting

State hoisting in Compose is a pattern of moving state to a composable's caller to make a composable stateless. The general pattern for state hoisting in Jetpack Compose is to replace the state variable with two parameters:

  • value: T: the current value to display
  • onValueChange: (T) -> Unit: an event that requests the value to change, where T is the proposed new value

However, you are not limited to onValueChange. If more specific events are appropriate for the composable you should define them using lambdas like ExpandingCard does with onExpand and onCollapse.

State that is hoisted this way has some important properties:

  • Single source of truth: By moving state instead of duplicating it, we're ensuring there's only one source of truth. This helps avoid bugs.
  • Encapsulated: Only stateful composables will be able to modify their state. It's completely internal.
  • Shareable: Hoisted state can be shared with multiple composables. Say we wanted to name in a different composable, hoisting would allow us to do that.
  • Interceptable: callers to the stateless composables can decide to ignore or modify events before changing the state.
  • Decoupled: the state for the stateless ExpandingCard may be stored anywhere. For example, it's now possible to move name into a ViewModel.

In the example case, you extract the name and the onValueChange out of HelloContent and move them up the tree to a HelloScreen composable that calls HelloContent.

@Composable
fun HelloScreen() {
    var name by rememberSaveable { mutableStateOf("") }

    HelloContent(name = name, onNameChange = { name = it })
}

@Composable
fun HelloContent(name: String, onNameChange: (String) -> Unit) {
    Column(modifier = Modifier.padding(16.dp)) {
        Text(
            text = "Hello, $name",
            modifier = Modifier.padding(bottom = 8.dp),
            style = MaterialTheme.typography.h5
        )
        OutlinedTextField(
            value = name,
            onValueChange = onNameChange,
            label = { Text("Name") }
        )
    }
}

By hoisting the state out of HelloContent, it's easier to reason about the composable, reuse it in different situations, and test. HelloContent is decoupled from how its state is stored. Decoupling means that if you modify or replace HelloScreen, you don't have to change how HelloContent is implemented.

The pattern where the state goes down, and events go up is called a unidirectional data flow. In this case, the state goes down from HelloScreen to HelloContent and events go up from HelloContent to HelloScreen. By following unidirectional data flow, you can decouple composables that display state in the UI from the parts of your app that store and change state.

Restoring state in Compose

Use rememberSaveable to restore your UI state after an activity or process is recreated. rememberSaveable retains state across recompositions. In addition, rememberSaveable also retains state across activity and process recreation.

Ways to store state

All data types that are added to the Bundle are saved automatically. If you want to save something that cannot be added to the Bundle, there are several options.

Parcelize

The simplest solution is to add the @Parcelize annotation to the object. The object becomes parcelable, and can be bundled. For example, this code makes a parcelable City data type and saves it to the state.

@Parcelize
data class City(val name: String, val country: String) : Parcelable

@Composable
fun CityScreen() {
    var selectedCity = rememberSaveable {
        mutableStateOf(City("Madrid", "Spain"))
    }
}

MapSaver

If for some reason @Parcelize is not suitable, you can use mapSaver to define your own rule for converting an object into a set of values that the system can save to the Bundle.

data class City(val name: String, val country: String)

val CitySaver = run {
    val nameKey = "Name"
    val countryKey = "Country"
    mapSaver(
        save = { mapOf(nameKey to it.name, countryKey to it.country) },
        restore = { City(it[nameKey] as String, it[countryKey] as String) }
    )
}

@Composable
fun CityScreen() {
    var selectedCity = rememberSaveable(stateSaver = CitySaver) {
        mutableStateOf(City("Madrid", "Spain"))
    }
}

ListSaver

To avoid needing to define the keys for the map, you can also use listSaver and use its indices as keys:

data class City(val name: String, val country: String)

val CitySaver = listSaver<City, Any>(
    save = { listOf(it.name, it.country) },
    restore = { City(it[0] as String, it[1] as String) }
)

@Composable
fun CityScreen() {
    var selectedCity = rememberSaveable(stateSaver = CitySaver) {
        mutableStateOf(City("Madrid", "Spain"))
    }
}

Managing state in Compose

Simple state hoisting can be managed in the composable functions itself. However, if the amount of state to keep track of increases, or the logic to perform in composable functions arises, it's a good practice to delegate the logic and state responsibilities to other classes: state holders.

This section covers how to manage state in different ways in Compose. Depending on the complexity of the composable, there are different alternatives to consider:

  • Composables for simple UI element state management.
  • State holders for complex UI element state management. They own UI elements' state and UI logic.
  • Architecture Components ViewModels as a special type of state holder in charge of providing access to the business logic and the screen or UI state.

State holders come in a variety of sizes depending on the scope of the corresponding UI elements they manage, ranging from a single widget like a bottom app bar to a whole screen. State holders are compoundable; that is, a state holder may be integrated into another state holder, especially when aggregating states.

The following diagram shows a summary of the relationships between the entities involved in Compose state management. The rest of the section covers each entity in detail:

  • A composable can depend on 0 or more state holders (that can be plain objects, ViewModels, or both) depending on its complexity.
  • A plain state holder might depend on a ViewModel if it needs access to the business logic or screen state.
  • A ViewModel depends on the business or data layers.

Diagram showing the dependencies in state management, as decribed in the preceding list.

Summary of the (optional) dependencies for each entity involved in Compose state management.

Types of state and logic

In an Android app, there are different types of state to consider:

  • UI element state is the hoisted state of UI elements. For example, ScaffoldState handles the state of the Scaffold composable.

  • Screen or UI state is what needs to be displayed on the screen. For example, a CartUiState class that can contain the Cart items, messages to show to the user or loading flags. This state is usually connected with other layers of the hierarchy because it contains application data.

And also, there are different types of logic:

  • UI behavior logic or UI logic is related to how to display state changes on the screen. For example, navigation logic decides which screen to show next, or UI logic that decides how to display user messages on the screen that could be using snackbars or toasts. The UI behavior logic should always live in the Composition.

  • Business logic is what to do with state changes. For example making a payment or storing user preferences. This logic is usually placed in the business or data layers, never in the UI layer.

Composables as source of truth

Having UI logic and UI elements state in composables is a good approach if the state and logic is simple. For example, here's the MyApp composable handling ScaffoldState and a CoroutineScope:

@Composable
fun MyApp() {
    MyTheme {
        val scaffoldState = rememberScaffoldState()
        val coroutineScope = rememberCoroutineScope()

        Scaffold(scaffoldState = scaffoldState) {
            MyContent(
                showSnackbar = { message ->
                    coroutineScope.launch {
                        scaffoldState.snackbarHostState.showSnackbar(message)
                    }
                }
            )
        }
    }
}

Because ScaffoldState contains mutable properties, all interactions with it should happen in the MyApp composable. Otherwise, if we pass it to other composables, they could mutate its state, which doesn't comply with the single source of truth principle and makes tracking down bugs more difficult.

State holders as source of truth

When a composable contains complex UI logic that involves multiple UI elements' state, it should delegate that responsibility to state holders. This makes this logic more testable in isolation, and reduces the composable's complexity. This approach favors the separation of concerns principle: the composable is in charge of emitting UI elements, and the state holder contains the UI logic and UI elements' state.

State holders are plain classes that are created and remembered in the Composition. Because they follow the composable's lifecycle, they can take Compose dependencies.

If our MyApp composable from the Composables as source of truth section grows in responsibilities, we can create a MyAppState state holder to manage its complexity:

// Plain class that manages App's UI logic and UI elements' state
class MyAppState(
    val scaffoldState: ScaffoldState,
    val navController: NavHostController,
    private val resources: Resources,
    /* ... */
) {
    val bottomBarTabs = /* State */

    // Logic to decide when to show the bottom bar
    val shouldShowBottomBar: Boolean
        @Composable get() = /* ... */

    // Navigation logic, which is a type of UI logic
    fun navigateToBottomBarRoute(route: String) { /* ... */ }

    // Show snackbar using Resources
    fun showSnackbar(message: String) { /* ... */ }
}

@Composable
fun rememberMyAppState(
    scaffoldState: ScaffoldState = rememberScaffoldState(),
    navController: NavHostController = rememberNavController(),
    resources: Resources = LocalContext.current.resources,
    /* ... */
) = remember(scaffoldState, navController, resources, /* ... */) {
    MyAppState(scaffoldState, navController, resources, /* ... */)
}

Because MyAppState takes dependencies, it's a good practice to provide a method that remembers an instance of MyAppState in the Composition. In this case, the rememberMyAppState function.

Now, MyApp is focused on emitting UI elements, and delegates all the UI logic and UI elements' state to MyAppState:

@Composable
fun MyApp() {
    MyTheme {
        val myAppState = rememberMyAppState()
        Scaffold(
            scaffoldState = myAppState.scaffoldState,
            bottomBar = {
                if (myAppState.shouldShowBottomBar) {
                    BottomBar(
                        tabs = myAppState.bottomBarTabs,
                        navigateToRoute = {
                            myAppState.navigateToBottomBarRoute(it)
                        }
                    )
                }
            }
        ) {
            NavHost(navController = myAppState.navController, "initial") { /* ... */ }
        }
    }
}

As you can see, incrementing a composable's responsibilities increases the need for a state holder. The responsibilities could be in UI logic, or just in the amount of state to keep track of.

ViewModels as source of truth

If plain state holders classes are in charge of the UI logic and UI elements' state, a ViewModel is a special type of state holder that is in charge of:

  • providing access to the business logic of the application that is usually placed in other layers of the hierarchy such as the business and data layers, and
  • preparing the application data for presentation in a particular screen, which becomes the screen or UI state.

ViewModels have a longer lifetime than the Composition because they survive configuration changes. They can follow the lifecycle of the host of Compose content–that is, activities or fragments–or the lifecycle of a destination or the Navigation graph if you're using the Navigation library. Because of their longer lifetime, ViewModels should not hold long-lived references to state bound to the lifetime of the Composition. If they do, it could cause memory leaks.

We recommend screen-level composables to use ViewModels for providing access to business logic and being the source of truth for their UI state. Check the ViewModel and state holders section to see why ViewModels are a good fit for this.

The following is an example of a ViewModel used in a screen-level composable:

data class ExampleUiState(
    dataToDisplayOnScreen: List<Example> = emptyList(),
    userMessages: List<Message> = emptyList(),
    loading: Boolean = false
)

class ExampleViewModel(
    private val repository: MyRepository,
    private val savedState: SavedStateHandle
) : ViewModel() {

    var uiState by mutableStateOf<ExampleUiState>(...)
        private set

    // Business logic
    fun somethingRelatedToBusinessLogic() { ... }
}

@Composable
fun ExampleScreen(viewModel: ExampleViewModel = viewModel()) {

    val uiState = viewModel.uiState
    ...

    Button(onClick = { viewModel.somethingRelatedToBusinessLogic() }) {
        Text("Do something")
    }
}

ViewModel and state holders

The benefits of ViewModels in Android development make them suitable for providing access to the business logic and preparing the application data for presentation on the screen. Namely, the benefits are:

  • Operations triggered by ViewModels survive configuration changes.
  • Integration with Navigation:
    • Navigation caches ViewModels while the screen is on the back stack. This is important to have your previously loaded data instantly available when you return to your destination. This is something more difficult to do with a state holder that follows the lifecycle of the composable screen.
    • The ViewModel is also cleared when the destination is popped off the back stack, ensuring that your state is automatically cleaned up. This is different from listening for the composable disposal that can happen for multiple reasons such as going to a new screen, due to a configuration change, etc.
  • Integration with other Jetpack libraries such as Hilt.

Because state holders are compoundable and ViewModels and plain state holders have different responsibilities, it's possible for a screen-level composable to have both a ViewModel that provides access to business logic AND a state holder that manages its UI logic and UI elements' state. Since ViewModels have a longer lifespan than state holders, state holders can take ViewModels as a dependency if needed.

The following code shows a ViewModel and plain state holder working together on an ExampleScreen:

private class ExampleState(
    val lazyListState: LazyListState,
    private val resources: Resources,
    private val expandedItems: List<Item> = emptyList()
) { ... }

@Composable
private fun rememberExampleState(...) { ... }

@Composable
fun ExampleScreen(viewModel: ExampleViewModel = viewModel()) {

    val uiState = viewModel.uiState
    val exampleState = rememberExampleState()

    LazyColumn(state = exampleState.lazyListState) {
        items(uiState.dataToDisplayOnScreen) { item ->
            if (exampleState.isExpandedItem(item) {
                ...
            }
            ...
        }
    }
}

Learn more

To learn more about state and Jetpack Compose, take the Using State in Jetpack Compose codelab.