0
0
Android-kotlinHow-ToBeginner ยท 4 min read

How to Use State in Compose in Android: Simple Guide

In Jetpack Compose, use remember and mutableStateOf to hold and update state inside composable functions. This lets your UI reactively update when the state changes.
๐Ÿ“

Syntax

To use state in Compose, declare a variable with remember and mutableStateOf. This creates a state holder that Compose tracks for changes.

  • remember: Keeps the state across recompositions.
  • mutableStateOf: Holds the actual value and triggers UI updates when changed.
kotlin
var count by remember { mutableStateOf(0) }
๐Ÿ’ป

Example

This example shows a button that increments a counter. The UI updates automatically when the button is clicked because the state changes.

kotlin
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.window.singleWindowApplication

fun main() = singleWindowApplication {
    var count by remember { mutableStateOf(0) }

    Button(onClick = { count++ }) {
        Text("Clicked $count times")
    }
}
Output
A window with a button labeled 'Clicked 0 times'. Each click updates the label to 'Clicked 1 time', 'Clicked 2 times', etc.
โš ๏ธ

Common Pitfalls

Common mistakes include:

  • Not using remember, causing state to reset on every recomposition.
  • Using regular variables instead of mutableStateOf, so UI does not update.
  • Modifying state outside of composable scope or without proper delegation.
kotlin
/* Wrong way: state resets on recomposition */
var count = 0

/* Right way: state remembered and triggers UI update */
var count by remember { mutableStateOf(0) }
๐Ÿ“Š

Quick Reference

ConceptDescription
rememberKeeps state across recompositions
mutableStateOfHolds a value and triggers UI updates on change
by keywordDelegates state variable to simplify syntax
State HoistingPass state up to parent composables for better control
โœ…

Key Takeaways

Use remember with mutableStateOf to create reactive state in Compose.
State changes automatically update the UI without manual refresh.
Always declare state inside composable functions to keep it consistent.
Avoid using plain variables for state as they won't trigger UI updates.
Consider state hoisting to manage state from parent composables.