Kotlin

Compose State Hoisting

admin by @admin ADMIN
5d ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
Lift state UP to where it's needed. A composable becomes "stateless" (taking `value` + `onValueChange`) which makes it reusable and testable. The Compose mantra.
Kotlin
Raw
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*

// ❌ Stateful — hard to test, can only show its own count
@Composable
fun StatefulCounter() {
    var count by remember { mutableStateOf(0) }
    Button(onClick = { count++ }) { Text("Count: $count") }
}

// ✅ Stateless — takes state from above
@Composable
fun StatelessCounter(count: Int, onIncrement: () -> Unit) {
    Button(onClick = onIncrement) { Text("Count: $count") }
}

// Parent owns the state — can also pass the same state to multiple children
@Composable
fun Parent() {
    var count by remember { mutableStateOf(0) }
    Column {
        StatelessCounter(count = count, onIncrement = { count++ })
        Text("Doubled: ${count * 2}")
        Button(onClick = { count = 0 }) { Text("Reset") }
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.