*[*:white_check_mark: SOLVED] *Subject*: `remember...
# compose
t
[ SOLVED] Subject:
rememberUpdateState
I’ve seen most of the
@Composables
are using
rememberUpdateState
before invoking a lambda. For eg,
BackHandler
internally calling
rememberUpdateState
on
onBack
lambda,
clickable
modifier calls on
onClick
lambda. Does that mean we should wrap all lambda with
rememberUpdateState
before invoking ? 🤔 If that’s the case, why can’t compiler do it for us? #possibly_a_stupid_question
👍 1
a
Have you checked the doc? I think it explains when you need to use
rememberUpdatedState
quite clearly.
t
@Albert Chang Yes. I already read that doc. That explains one of the usecases of
rememberUpdateState
with
LaunchedEffect
. But what am asking is, basically we use
rememberUpdateState
to get the latest value (or to avoid stale value). Is there a scenario where we need to access the stale value? 🤔
a
The point is whether there is a long-living lambda (or function) that captures the value. If there isn't such a lambda, there is no need to use
rememberUpdatedState
.
t
Hmm. but Lambdas are mostly long-living functions or mostly used at later time (or after the composition). For example,
onClick
,
onBack
etc. So lambas without
rememberUpdatedState
should be very rare?
a
No, most lambdas are not long-living. In a composable function, if the dependencies of a lambda (i.e. the variables it captures) change, a new lambda instance will be created.
By saying long-living I mean it survives recomposition.
t
okay, so basically, I only need to use
rememberUpdatedState
if and only if am accessing a lambda in an area where recomposition can’t be reached. For example,
remember
,
LaunchedEffect
, etc.. is that what you’re saying ?
a
Yep. But for
remember
, it's better to just use it as a key.
t
ahaa.. got it.
so here they used
rememberUpdateState
because its easier better than recreating the
DisposableEffect
?
i mean, if the code is something like this
they don’t need
rememberUpdateState
here.
a
Yeah
OnBackPressedDispatcher
is designed that way.
t
Got it. thank you so much for bearing with me 😄
👍 1
r
See also related DX feature request: https://issuetracker.google.com/issues/217570480