DEV Community

Cover image for Understanding State in Jetpack Compose (Simple Guide for Beginners)
MD IBRAHIM KHALIL
MD IBRAHIM KHALIL

Posted on

Understanding State in Jetpack Compose (Simple Guide for Beginners)

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")
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

🧠 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
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ This resets on every recomposition.

❌ Mistake 2: Doing heavy work in Composable

@Composable
fun BadExample() {
    val data = fetchDataFromNetwork() // ❌ Don't do this
}
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ 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)
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ 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)