CodeBlanks Logo Icon CodeBlanks

remember

Learn state retention with remember.

What is remember?

remember is a function that keeps a value across recompositions inside a composable. Compose does not reset variables on every redraw; remember stores them.

Example: val count = remember { mutableStateOf(0) }. This line creates the counter on the first draw and returns the same instance on later draws. Without remember, it would reset on every recomposition. This is the core way to keep UI state. The rememberInfo model in this lesson shows the concept.

A remember example

A counter composable holds state with remember. When the button is pressed, the counter increases and Compose redraws the related composable.

Example: val count = remember { mutableStateOf(0) }, then Button(onClick = { count.value++ }) { Text("${'$'}{count.value}") }. Each press increases count.value; Compose observes it and redraws the Text. remember keeps the counter without reset. This is the basis of reactive UI.

Practice Write rememberInfo

Define fun rememberInfo(): String. It should return "remember". In main, write println(rememberInfo()).

Starter code

Main.kt
// add the rememberInfo function

fun main() {
    // print the remember info
}

Sample solution

Main.kt
fun rememberInfo(): String = "remember"
fun main() {
    println(rememberInfo())
}

Expected output

remember

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the remember parts

Term Meaning
remember State retention
recomposition Redraw
mutableStateOf Reactive state
Composable UI function

2 When does remember reset?

Main.kt
remember lasts the composable lifetime.
  • On every recomposition
  • Until the app closes
  • Until the component leaves the tree Correct answer
  • Never

Explanation: remember keeps the value until the composable leaves the tree.

3 Complete the remember call

Question
val count = remember { ____ }
Answer
val count = remember { mutableStateOf(0) }

Explanation: remember { mutableStateOf(0) } stores the reactive counter.

All lessons in Expert