VOOZH about

URL: https://dev.to/mdibrahimk/understanding-state-in-jetpack-compose-simple-guide-for-beginners-f43

⇱ Understanding State in Jetpack Compose (Simple Guide for Beginners) - DEV Community


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”