When I first started learning Jetpack Compose, one concept confused me a lot: State.
But once I understood it, everything became much easier.
Let me explain it in a simple way π
π What is State?
Think of State like a light switch.
- When the switch changes β the light updates
- When state changes β the UI updates
In Jetpack Compose, UI is automatically redrawn when state changes.
π§© Basic Example
@Composable
fun CounterScreen() {
var count by remember { mutableStateOf(0) }
Column {
Text(text = "Count: $count")
Button(onClick = { count++ }) {
Text("Increase")
}
}
}
π§ Whatβs happening here?
-
rememberβ keeps value during recomposition -
mutableStateOfβ creates observable state -
count++β updates state β UI updates automatically
π You donβt manually refresh UI. Compose does it for you.
β οΈ Common Beginner Mistakes
β Mistake 1: Not using remember
var count = 0 // WRONG
π This resets on every recomposition.
β Mistake 2: Doing heavy work in Composable
@Composable
fun BadExample() {
val data = fetchDataFromNetwork() // β Don't do this
}
π This blocks UI and can cause lag.
βοΈ Use ViewModel + Coroutines instead.
ποΈ Recommended Pattern (Simple MVVM)
- UI β shows state
- ViewModel β holds state
- Repository β handles data
π Keep your Composable stateless when possible
Use State hoisting:
@Composable
fun Counter(count: Int, onIncrease: () -> Unit)
π This makes your UI reusable and clean.
π― Final Thought
If you understand State, you understand Compose.
Everything in Compose depends on:
βState changes β UI updatesβ
Top comments (0)