State Management in Jetpack Compose: remember & UDF

In Jetpack Compose, State is any value that can change over time — whether it is a string entered into a text field, a network loading spinner status, or the items in an e-commerce cart. In this class, we master how to create, remember, preserve, and hoist state across your UI architecture.

Understanding remember and mutableStateOf

Compose uses mutableStateOf(value) to create an observable state holder. The Compose runtime tracks every Composable that reads this value. When the value mutates, Compose schedules a Recomposition of those specific functions:

import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember

@Composable
fun CounterWidget() {
    // remember keeps the state alive across recompositions
    var count by remember { mutableStateOf(0) }

    Button(onClick = { count++ }) {
        Text("Total Clicks: $count")
    }
}

What happens if you omit remember?

If you write var count by mutableStateOf(0) without remember, the variable will be reinitialized back to 0 on every single recomposition! remember acts as a cache that preserves the state value across recompositions.

Handling Screen Rotation: rememberSaveable

While remember survives recomposition, it does not survive Activity configuration changes (such as rotating the phone between portrait and landscape or system language changes). To preserve state across configuration changes, use rememberSaveable, which automatically serializes values into an Android Bundle:

import androidx.compose.runtime.saveable.rememberSaveable

@Composable
fun UserInputBox() {
    // Survives screen rotation and process death!
    var searchKeyword by rememberSaveable { mutableStateOf("") }

    TextField(
        value = searchKeyword,
        onValueChange = { searchKeyword = it },
        label = { Text("Search Tutorials...") }
    )
}

State Hoisting (Unidirectional Data Flow Pattern)

State Hoisting is the fundamental architectural pattern in Compose where you move state up to a caller to make a Composable stateless, reusable, and easy to test. A hoisted composable has two parameters:

  • value: T — The current value to display (flows down).
  • onValueChange: (T) -> Unit — An event lambda to notify the parent to mutate the state (flows up).
// 1. Stateless, highly reusable child composable
@Composable
fun QuantitySelector(
    quantity: Int,
    onQuantityChange: (Int) -> Unit,
    modifier: Modifier = Modifier
) {
    Row(modifier = modifier, verticalAlignment = Alignment.CenterVertically) {
        IconButton(onClick = { if (quantity > 1) onQuantityChange(quantity - 1) }) {
            Text("-", fontSize = 24.sp, fontWeight = FontWeight.Bold)
        }
        Text("$quantity", modifier = Modifier.padding(horizontal = 12.dp))
        IconButton(onClick = { onQuantityChange(quantity + 1) }) {
            Text("+", fontSize = 24.sp, fontWeight = FontWeight.Bold)
        }
    }
}

// 2. Stateful parent composable (or ViewModel)
@Composable
fun CartItemScreen() {
    var itemCount by rememberSaveable { mutableStateOf(1) }

    Column(modifier = Modifier.padding(16.dp)) {
        Text("Product: Android Kotlin Master Course")
        QuantitySelector(
            quantity = itemCount,
            onQuantityChange = { newItemCount -> itemCount = newItemCount }
        )
    }
}

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What is the difference between remember and rememberSaveable?

`remember` persists state only during recompositions within the current Activity instance. `rememberSaveable` persists state both during recompositions AND through Activity recreation events like screen rotation and OS-initiated background process recreation.

Q2. Why is stateless composable design preferred in Jetpack Compose?

Stateless composables do not own or mutate state directly; they simply accept data and emit events. This makes them 100% reusable across different screens, easily viewable in Android Studio @Preview panels, and simple to unit test without mocking state frameworks.

Q3. How does Compose know which composables to skip during recomposition?

Compose compares parameter values. If a composable function receives stable, unchanged parameters (like primitive types or Kotlin data classes with val properties), the compiler skips executing that function entirely during recomposition (smart recomposition).

Explore Related Android Development Classes & Next Steps

Broaden your foundational and advanced Android application development skills across our curriculum:

Jetpack Compose Fundamentals

Review basic composable tree creation and layout principles.

ViewModel & StateFlow

Connect UI state hoisting directly to AAC ViewModel StateFlow.

Clean Architecture & MVVM/MVI

Understand unidirectional data flow (UDF) across architecture layers.

LazyColumn & Item State

Preserve scroll state and item selection in lazy lists.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Reddit

You may also like this!