0
0
Android Kotlinmobile~5 mins

rememberSaveable for configuration changes in Android Kotlin

Choose your learning style9 modes available
Introduction

We use rememberSaveable to keep data safe when the screen changes, like rotating the phone. It helps keep your app's state without losing it.

When you want to keep user input in a text box after rotating the device.
When you want to save a counter value during configuration changes like dark mode switch.
When you want to keep the state of a toggle button after the screen size changes.
When you want to preserve scroll position in a list after device rotation.
Syntax
Android Kotlin
val state = rememberSaveable { mutableStateOf(initialValue) }

rememberSaveable works like remember but also saves state across configuration changes.

You can use it with simple types like Int, String, Boolean, or with custom types if you provide a saver.

Examples
This saves an integer counter that survives screen rotations.
Android Kotlin
val count = rememberSaveable { mutableStateOf(0) }
This saves a string input, like a user name, across configuration changes.
Android Kotlin
val name = rememberSaveable { mutableStateOf("") }
This saves a boolean toggle state, like a checkbox, even if the device rotates.
Android Kotlin
val isChecked = rememberSaveable { mutableStateOf(false) }
Sample App

This app has a text input and a button showing how many times it was clicked. Both the typed name and click count stay the same even if you rotate the device.

Android Kotlin
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.rememberSaveable
import androidx.compose.ui.tooling.preview.Preview

@Composable
fun RememberSaveableExample() {
  val name = rememberSaveable { mutableStateOf("") }
  val count = rememberSaveable { mutableStateOf(0) }

  Column {
    TextField(
      value = name.value,
      onValueChange = { name.value = it },
      label = { Text("Enter your name") }
    )
    Button(onClick = { count.value++ }) {
      Text("Clicks: ${count.value}")
    }
  }
}

@Preview
@Composable
fun PreviewRememberSaveableExample() {
  RememberSaveableExample()
}
OutputSuccess
Important Notes

rememberSaveable automatically saves simple types like Int, String, and Boolean.

For complex objects, you need to provide a custom saver to rememberSaveable.

This helps avoid losing user data during common changes like screen rotation or language change.

Summary

rememberSaveable keeps your UI state safe during configuration changes.

Use it for user inputs, counters, toggles, and other simple states.

It works like remember but adds automatic saving and restoring.