https://kotlinlang.org logo
#compose
Title
# compose
d

Dominaezzz

12/02/2020, 11:31 PM
derivedStateOf
vs
remember
. When should I prefer one over the other?
z

Zach Klippenstein (he/him) [MOD]

12/02/2020, 11:59 PM
derivedStateOf is for when you need to read State objects to calculate your value. If you already have a State, it might be a good fit. Remember takes explicit keys, so it can handle that as well but is a bit more verbose. If you find yourself writing something like
Copy code
val input: State<Int> = …
val
state by remember {
Copy code
mutableStateOf(input.value * 2)
}.apply { value = input.value * 2 }
hen it might be time for derivedStateOf
👍 1
Wow slack is useless, just ate an entire paragraph I typed in that message 🤦‍♂️
Anyway if you excuse that garbage formatting, if you’re remembering a mutable state and updating it yourself, that’s when you might be able to use derivedStateOf
👍 4
d

Dominaezzz

12/03/2020, 12:28 AM
Ah thanks. I'll be using that
derivedStateOf
more now.
o

Orhan Tozan

12/03/2020, 2:17 PM
From what I remember, you don't need derivedStateOf. You can just do val sum = a + b
z

Zach Klippenstein (he/him) [MOD]

12/03/2020, 6:19 PM
Yes, for this example, you can just do the calculation. In a real use case, you’d presumably be doing some more expensive calculation.