0
0
Android Kotlinmobile~5 mins

Recomposition concept in Android Kotlin

Choose your learning style9 modes available
Introduction

Recomposition lets your app update the screen automatically when data changes. It helps keep the app UI fresh without extra work.

When you want to show updated information after a user action, like clicking a button.
When data changes in your app and you want the screen to reflect those changes immediately.
When building interactive UI components that depend on user input or live data.
When you want to avoid manually refreshing or redrawing parts of your app screen.
Syntax
Android Kotlin
@Composable
fun Greeting(name: String) {
  Text(text = "Hello, $name!")
}
Use @Composable to mark functions that describe UI.
Recomposition happens automatically when parameters or state used inside change.
Examples
This simple composable shows a greeting. If name changes, the UI updates automatically.
Android Kotlin
@Composable
fun Greeting(name: String) {
  Text(text = "Hello, $name!")
}
This example uses state. When count changes, the button text updates by recomposition.
Android Kotlin
@Composable
fun Counter() {
  var count by remember { mutableStateOf(0) }
  Button(onClick = { count++ }) {
    Text("Clicked $count times")
  }
}
Sample App

This app shows a greeting and a button. When you click the button, the name changes and the greeting updates automatically because of recomposition.

Android Kotlin
import androidx.compose.material3.*
import androidx.compose.foundation.layout.Column
import androidx.compose.runtime.*
import androidx.compose.ui.window.singleWindowApplication

fun main() = singleWindowApplication {
  var name by remember { mutableStateOf("World") }

  Column {
    Text(text = "Hello, $name!", style = MaterialTheme.typography.headlineMedium)
    Button(onClick = { name = "Compose" }) {
      Text("Change Name")
    }
  }
}
OutputSuccess
Important Notes

Recomposition only updates the parts of the UI that depend on changed data, making it efficient.

Use remember and mutableStateOf to hold state that triggers recomposition.

Too many unnecessary recompositions can slow your app, so keep state minimal and focused.

Summary

Recomposition updates UI automatically when data changes.

Use @Composable functions with state to enable recomposition.

It helps build interactive and responsive apps easily.