am reading side effects documentation and I have a...
# compose
m
am reading side effects documentation and I have a bit of a trouble grasping
rememberUpdatedState
. what is it used for and what is it really doing? am trying to write some code in order to test/grasp what’s it doing but still nothing
z
Look at the code, it’s super simple, so if you understand the building blocks it might make a lot more sense:
Copy code
@Composable
fun <T> rememberUpdatedState(newValue: T): State<T> = remember {
    mutableStateOf(newValue)
}.apply { value = newValue }
As for how to use it, I think a reasonable general rule is any time you’re referencing parameter to a composable function in a lambda or function that will not be re-created on each composition (e.g. a side effect lambda, or an event handler, any function you’re storing in a class), you’ll want to use it. Otherwise, the first composition will create an instance for your lambda which captures the parameter value, but if that value changes and causes a recomposition, a new instance of that lambda will be created that captures the new value – the initial lambda instance will still only have a reference to the initial value.
rememberUpdatedState
ensures that new values from future recompositions will be seen by lambdas that live over a longer time frame (i.e. multiple compositions).
m
thanks