Compose needs to know which data, when it changes, should trigger recomposition. mutableStateOf creates an observable holder; reading it inside a composable subscribes that composable to it, so assigning a new value re-runs exactly the functions that read it and nothing else.
A plain local variable would be reset on every recomposition, so state must be wrapped in remember, which preserves a value across recompositions of the same composable. remember does not survive configuration changes - rememberSaveable does, by writing to the saved instance state bundle.
State hoisting is the pattern that makes composables reusable and testable. Instead of a composable owning its state, it takes the current value as a parameter and an onValueChange callback, pushing ownership to the caller. A composable with no state of its own is called stateless, it renders identically for identical inputs, and it can be previewed and tested trivially. The rule of thumb is to hoist state to the lowest common ancestor of everything that needs it.
The by delegate from level three removes the .value noise: var text by remember { mutableStateOf("") } reads and writes like an ordinary var while remaining observable.
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
// STATELESS: takes its value in, reports changes out. Trivially previewable.
@Composable
fun SearchField(query: String, onQueryChange: (String) -> Unit) {
OutlinedTextField(
value = query,
onValueChange = onQueryChange,
label = { Text("Search") },
modifier = Modifier.fillMaxWidth(),
)
}
// STATEFUL: owns the state and passes it down. The by delegate hides .value.
@Composable
fun SearchScreen(allNotes: List<String>) {
var query by rememberSaveable { mutableStateOf("") }
val matches = remember(query, allNotes) {
allNotes.filter { it.contains(query, ignoreCase = true) }
}
Column(Modifier.padding(16.dp)) {
SearchField(query = query, onQueryChange = { query = it })
Spacer(Modifier.height(8.dp))
matches.forEach { Text(it) }
if (matches.isEmpty()) Text("No matches")
}
}
Discussion
No questions on this topic yet. Sign in to ask the first one.