State holds the current information your app shows. When state changes, the app updates what you see automatically.
0
0
Why state drives UI updates in Android Kotlin
Introduction
When you want to show a counter that changes when a button is clicked.
When you need to update a list after adding or removing items.
When showing different screens or messages based on user actions.
When reflecting user input immediately on the screen.
When toggling between light and dark mode in your app.
Syntax
Android Kotlin
var stateVariable = initialValue // When stateVariable changes, UI updates automatically
In Android with Kotlin, state is often managed using var variables inside ViewModel or MutableStateFlow.
Changing the state triggers UI to redraw with new data.
Examples
A simple number that changes and updates the screen.
Android Kotlin
var counter = 0 // Increase counter and UI updates
Boolean state to show or hide parts of UI.
Android Kotlin
var isLoading = false // Show loading spinner when true
String state to show text entered by user.
Android Kotlin
var userName = "" // Display user name after input
Sample App
This app shows a button with a number. Each time you tap the button, the number increases. The number is stored in count state. When count changes, the button text updates automatically.
Android Kotlin
import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.tooling.preview.Preview class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { CounterApp() } } } @Composable fun CounterApp() { var count by remember { mutableStateOf(0) } Button(onClick = { count++ }) { Text(text = "Clicked $count times") } } @Preview(showBackground = true) @Composable fun PreviewCounterApp() { CounterApp() }
OutputSuccess
Important Notes
State must be mutable and remembered to update UI in Compose.
Changing state triggers recomposition, which redraws UI parts that depend on that state.
Keep state minimal and only for data that affects UI.
Summary
State holds the current data shown on screen.
When state changes, UI updates automatically to match.
Using state makes apps interactive and responsive to user actions.