Jetpack Compose Concepts

Compose Optimizations

Compose wants to be as efficient as possible, so during recomposition, it looks at parameter values being passed into nested composable functions and see it can skip the nested part. Take a look at

data class Person(
    val name: String,
    val age: Int,
)

@Composable
fun AgeStuff(age: Int) { ... }

@Composable
fun PersonStuff(person: Person) {
    ...
    AgeStuff(person.age)
}

...

var `person` by mutableStateOf(Person("Scott", 22))
PersonStuff(person)

This will compose PersonStuff which in turn calls and composes AgeStuff.

At some point, suppose that we set person = Person("Mike", 22). Note that the age hasn't changed.

Because person is different, we'll recompose PersonStuff, but when Compose looks at the parameter passed to AgeStuff it realizes the value hasn't changed, and it can skip recomposing it!

But how does Compose actually know this is safe to do?

Immutable state is state that cannot change. Compose can look at the value of the state and know that if it's looking at the same value, it could not have changed, no matter how deep the data. Basic Kotlin types such as Int, Char and String are immutable, as are containing types that only contain immutable values (and provide no way to mutate them).

Stable state may change, but it's controlled in a way that Compose can observe. We've seen MutableState, which interacts with the snapshot system to inform Compose that values have changed.

When the Compose compiler plugin analyzes your code, it marks each function that only takes stable or immutable data as "skippable". In the previous example, AgeStuff was skippable because it took an immutable value, age: Int, as its only parameter. When running, it knows it can skip recomposition of AgeStuff if the new and old values are the same.

You really only have to worry about this when optimizing your composable functions. For more details on optmization, see Stability in Compose and Jetpack Compose Stability Explained. Be careful not to prematurely optimize, but this is good info to help you understand what's happening behind the scenes.