This is a simple Jetpack Compose tutorial to learn basic state management by creating a counter. A Text composable shows the number of counts whereas a Button is used to increment the count.
For every button click, the UI should be updated with the latest number of counts. Therefore, we need to utilize state management in this situation. Using remember API and MutableState together we can get the desired outcome.
@Composable
fun CounterExample() {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
val count: MutableState<Int> = remember {
mutableStateOf(0)
}
Text(text = "The current count is ${count.value} ")
Button(onClick = { count.value++ }) {
Text(text = "Add")
}
}
}
When the button is pressed the count value is changed and will be reflected on UI. See the output given below.

Following is the complete code for reference.
package com.example.myapplication
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.myapplication.ui.theme.MyApplicationTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyApplicationTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
CounterExample()
}
}
}
}
}
@Composable
fun CounterExample() {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
val count: MutableState<Int> = remember {
mutableStateOf(0)
}
Text(text = "The current count is ${count.value} ")
Button(onClick = { count.value++ }) {
Text(text = "Add")
}
}
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
MyApplicationTheme {
CounterExample()
}
}
State management in Jetpack Compose is a vast topic and you can learn more from here. This small example of counter will help you to understand the basic state management.