myanmarking
01/12/2022, 5:46 PMfun someComposable(enabled: Boolean){
var valueField by remember{
mutableStateOf(..)
}
val errorInternal: Boolean = remember(enabled, valueField) {
derivedStateOf(valueField && enabled)
}
}
I need a state that depends on another state and a variable. derivedStateOf is for state only. This works but is this the correct approach?Casey Brooks
01/12/2022, 5:48 PMrememberUpdatedState()
? Putting derivedStateOf
in a remember { }
block seems wrong to me, though I can't really articulate why...myanmarking
01/12/2022, 5:53 PMfun someComposable(enabled: Boolean){
var valueField by remember{
mutableStateOf(..)
}
val _enabled = rememberUpdatedState(enabled)
val errorInternal by derivedStateOf(valueField && enabled)}
}
Casey Brooks
01/12/2022, 5:59 PMerrorInternal
is fast, you probably don't need to do that at all. derivedStateOf
is more of a cache for expensive operations that depend on state values, rather than a requirement for computations based on state values. there's nothing wrong with computing simple values directly within the composable functionmyanmarking
01/12/2022, 6:03 PMCasey Brooks
01/12/2022, 6:07 PMmyanmarking
01/12/2022, 6:10 PMCasey Brooks
01/12/2022, 6:13 PMAlex Vanyo
01/12/2022, 6:22 PMfun someComposable(enabled: Boolean){
var valueField by remember {
mutableStateOf(...)
}
val errorInternal = valueField && enabled
}
Casey is exactly right that derivedStateOf
is a caching mechanism. It has its uses for fine-tuning when things recompose, but you shouldn’t really need to do that tuning unless you have a noticeable performance reason to do so.
Just like any other caching mechanisms, you have to be more careful to invalidate the cache at the right time to see a tangible benefit without having subtle state issuesZach Klippenstein (he/him) [MOD]
01/12/2022, 10:30 PMderivedStateOf
from a composition directly, you definitely need to put it in a remember
otherwise you’re re-creating the state every time, just like if you use mutableStateOf
without a remember
.lhwdev
01/13/2022, 5:00 AMderivedStateOf
itself seems to be quite heavy to me. Also derivedStateOf can be used outside Compose.
Thinking if something can be used outside Compose is also a great criteria like:
class Model {
val a by mutableStateOf { 1 }
val b by derivedStateOf { a - 3 }
}
States (and snapshot-related apis) are not that compose-specific. In fact I use them to manage states out of Compose.