androidkotlinandroid-jetpack-composecompose-recomposition

Difference between remember and rememberUpdatedState in Jetpack Compose?


I'm confused, can someone explain me the difference between:

val variable by remember { mutableStateOf() }

and

val variable by rememberUpdatedState()

When I check the source code of rememberUpdatedStates I actually see: remember { mutableStateOf() }

@Composable
fun <T> rememberUpdatedState(newValue: T): State<T> = remember {
    mutableStateOf(newValue)
}.apply { value = newValue }

Solution

  • remember is needed when you don't want to do some heavy calculation/operation when your composable is recomposed. On the other hand, sometimes your operation might change so you need to do calculations or update remembered values to make sure not to use obsolete values from the initial calculation.

    fun <T> rememberUpdatedState(newValue: T): State<T> = remember {
        mutableStateOf(newValue)
    }.apply { value = newValue }
    

    rememberUpdatedState function is the same as using remember with mutableState to trigger recomposition when value changes.

    @Composable
    private fun Calculation(input: Int) {
        val rememberUpdatedStateInput by rememberUpdatedState(input)
        val rememberedInput = remember { input }
    
        Text("updatedInput: $rememberUpdatedStateInput, rememberedInput: $rememberedInput")
    }
    
    var myInput by remember {
        mutableStateOf(0)
    }
    
    OutlinedButton(
        onClick = {
            myInput++
    
        }
    ) {
        Text("Increase $myInput")
    }
    Calculation(input = myInput)
    

    This is a very basic example to show how values from remember and rememberUpdatedState change.

    A more practical example is with lambdas.

    For example, suppose your app has a LandingScreen that disappears after some time. Even if LandingScreen is recomposed, the effect that waits for some time and notifies that the time passed shouldn't be restarted:

    @Composable
    fun LandingScreen(onTimeout: () -> Unit) {
    
        // This will always refer to the latest onTimeout function that
        // LandingScreen was recomposed with
        val currentOnTimeout by rememberUpdatedState(onTimeout)
    
        // Create an effect that matches the lifecycle of LandingScreen.
        // If LandingScreen recomposes, the delay shouldn't start again.
        LaunchedEffect(true) {
            delay(SplashWaitTimeMillis)
            currentOnTimeout()
        }
    
        /* Landing screen content */
    }
    

    In this example LaunchedEffect is invoked once but this LandingScreen function can be recomposed and might require you to change onTimeOut, so using rememberUpdatedState makes sure that the latest onTimeout is called after delay.