kotlinandroid-jetpack-composejetbrains-compose

Compose: remember() with keys vs. derivedStateOf()


What is the difference between these two approaches?

  1. val result = remember(key1, key2) { computeIt(key1, key2) } (Docs)
  2. val result by remember { derivedStateOf { computeIt(key1, key2) } } (Docs)

Both avoid re-computation if neither key1 nor key2 has changed . The second also avoids re-computations if downstream states are derived, but else, they are identical in their behavior, aren't they?


Solution

  • AFAIK there is no difference here. It's just a coincidence that both constructs are doing the same thing here in this context. But, there are differences!

    The biggest one is that derivedStateOf is not composable and it does no caching on it's own (remember does). So derivedStateOf is meant for long running calculations that have to be run only if key changes. Or it can be used to merge multiple states that are not in composable (in custom class for example).

    I think the exact explanation is blurred for "outsiders", we need some input from some compose team member here :). My source for the above is this one thread on slack and my own experiments

    EDIT:

    Today i learned another derivedStateOf usage, very important one. It can be used to limit recomposition count when using some very frequently used value for calculation.

    Example:

    // we have a variable scrollState: Int that gets updated every time user scrolls
    // we want to update our counter for every 100 pixels scrolled.
    // To avoid recomposition every single pixel change we are using derivedStateOf
    val counter = remember {
        derivedStateOf {
            (scrollState / 100).roundToInt()
        }
    }
    
    // this will be recomposed only on counter change, so it will "ignore" scrollState in 99% of cases
    Text(counter.toString()).
    

    My source for that is as direct as it can be - from the author of compose runtime and the snapshot system, the Chuck Jazdzewski himself. I highly recommend watching stream with him here: https://www.youtube.com/watch?v=waJ_dklg6fU

    EDIT2:

    We finally have some official performance documentation with small mention of derivedStateOf. So the official purpose of derivedStateOf is to limit composition count (like in my example). sauce