Compose basics
State, recomposition and modifiers
Compose describes UI through composable functions. Observable state changes can invalidate the scopes that read them. A read during layout or drawing may restart only that phase instead of composition. Compose phases.
State
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
@Composable
fun Greeting() {
var name by remember { mutableStateOf("") }
Column {
TextField(value = name, onValueChange = { name = it })
Text("Hello, $name")
}
}
mutableStateOf is observable; its default equality policy ignores an assignment equal by ==. remember retains a value at its composition position until removal or key change. rememberSaveable also supports restoring small UI values after Activity recreation, within saved-state limits. State, saving state.
State hoisting
Pass a value and an event callback to a reusable component. Place ownership at the lowest common owner that needs to read or change it; a ViewModel is one possible owner, not a requirement for every field. State hoisting.
Modifiers and effects
Padding before a background lies outside the painted area; padding after it lies inside. Order also affects click targets. Modifiers.
LaunchedEffect(key) cancels and restarts when a key changes and cancels on leaving composition. A constant key means once per entry, not once per application. Effects.
Strong skipping is enabled by default since Kotlin 2.0.20. It permits skipping restartable composables with unstable parameters; it does not make mutable collections observable or stable. Strong skipping, stability.