Jetpack Compose State — Complete Guide
In this tutorial, you'll learn about Jetpack Compose State. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
Your Composable recomposes infinitely, the text field loses its value when the keyboard closes, or multiple components fight over the same state.
Wrong Approach ❌
@Composable
fun BadCounter() {
var count = 0 // Not observed — UI never updates
Column {
Text("Count: $count")
Button(onClick = { count++ }) { Text("Increment") }
}
}
@Composable
fun InfiniteRecomposer() {
var state by remember { mutableStateOf(0) }
// Side effect triggers during composition => infinite loop
state++ // DON'T DO THIS
Text("$state")
}
Output: Counter never updates. Infinite recomposition loop.
Right Approach ✅
@Composable
fun GoodCounter() {
var count by remember { mutableStateOf(0) }
Column {
Text("Count: $count")
Button(onClick = { count++ }) { Text("Increment") }
}
}
// State hoisted to parent
@Composable
fun Parent() {
var name by remember { mutableStateOf("") }
Child(name = name, onNameChange = { name = it })
}
@Composable
fun Child(name: String, onNameChange: (String) -> Unit) {
TextField(value = name, onValueChange = onNameChange)
}
Output: Reactive counter with proper recomposition. State survives keyboard changes.
Prevention
- Always use
mutableStateOf,StateFlow, orLiveDatafor observable state. - Use
rememberto preserve state across recompositions. - Hoist state to the lowest common ancestor that needs it.
- Never mutate state directly during composition (use
LaunchedEffect).
Common Mistakes with compose state
- Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
These mistakes appear frequently in real-world Android code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro