I have asked a similar question before here when I...
# compose
v
I have asked a similar question before here when I was just starting with compose but I still feel a bit confused now that I ran into this section of the documentation: Defer reads as long as possible (https://developer.android.com/jetpack/compose/performance#defer-reads) which states:
You should defer reading state variables as long as possible. Deferring state reads can help ensure that Compose re-runs the minimum possible code on recomposition. For example, if your UI has state that is hoisted high up in the composable tree and you read the state in a child composable, you can wrap the state read in a lambda function. Doing this makes the read occur only when it is actually needed.
All other documentation and examples seem to prefer passing only immutable data classes for state -- is this deferring technique recommended only for the most intensive cases (for example animations with values changing every frame)? To my understanding, when a value changes, the whole scope that read it is recomposed, including all child composables (unless the inputs are @Stable in which case all of the inputs will be diffed and recomposed only if the inputs are different). What is the downside of doing deferred reads and passing
State
, how much overhead does it add compared to diffing all parameters of invalidated child composables in a large invalidated scope? Also, does it matter how the state read is deferred? I have preferred not to use the delegate syntax for mutableStateOf so I can easily pass
State<T>
objects directly to child composables. Is there some reason why the provided example uses a callback and not something like this:
@Composable fun Child(state: State<T>) { state.value }
?
o
If I did not overlook something, your understanding is entirely correct. The reason you are seeing values passed into composables is that it's simpler to do and reason about. It can be less efficient with respect to recompositions as you have noted, which mostly seems to be an issue with animations frequently changing values. On how to defer the state read and why you might want to prefer a lambda parameter, this: https://kotlinlang.slack.com/archives/CJLTWPH7S/p1650307518585179?thread_ts=1650289906.051689&amp;cid=CJLTWPH7S
v
Thanks 😄
It feels like there's so much knowledge buried in threads here that are hard to discover
o
That's true, I'm keeping an archive of stuff and pulled out the link above from that. But congratulations, you already got everything right, so it's basically just a confirmation. 👏🙂