Android Kotlin — remember() with keys vs. derivedStateOf()

Maneesha Erandi
2 min readApr 1, 2024
Photo by Louis Tsai on Unsplash

Managing the state is a very important topic in mobile development. In a mobile app, the UI will change according to the user's actions all the time. What we have to consider is whether we are using the correct methods and APIs to make the process more optimized.

Jetpack Compose offers APIs to make managing the app state easy. When we want to update the same composable with new arguments that affect the UI, recomposition will take place.

We use remember() with keys and derivedStateOf{} for similar work in updating the UI according to state changes. But we have to consider performance as a factor when we choose one of them.

remember() with keys

  • function is used to keep state information within a composable function
  • when calling, compose ensures that the provided value is preserved across recompositions of the composable function
  • by default, Compose recomposes whenever there’s a change in the input data or state
  • when using with keys, we can control when recomposition should happen
  • using keys allows us to make the state with specific instances of the composable function unique
@Composable
fun Counter(key: String) {
var count by remember(key)…

--

--