5 Common mistakes in Jetpack Compose

HariAgusWidakdo
2 min readNov 4, 2024

--

Hi everyone, I will try to share 5 mistakes that are often made in writing in Jetpack Compose along with the solution :

1. Inefficient Modifiers

Using modifiers in the wrong order, such as putting .fillMaxSize() before .padding()

// Incorrect: Using fillMaxSize before padding
Box(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
) {
Text("Hello Jetpack Compose")
}

Solution :

Box(
modifier = Modifier
.padding(16.dp)
.fillMaxSize()
) {
Text("Hello Jetpack Compose")
}

2. Overcomposition

Breaking the UI into components that are too small, this can hinder perfomance and make the code unmanageable. If the component is not too complex there is no need to break it up.

@Composable
fun Title() {
Text("Welcome", fontSize = 24.sp)
}

@Composable
fun Subtitle() {
Text("This is Jetpack Compose", fontSize = 16.sp)
}

@Composable
fun Content() {
Column {
Title()
Subtitle()
}
}

Solution :

fun WelcomeContent() {
Column {
Text("Welcome", fontSize = 24.sp)
Text("This is Jetpack Compose", fontSize = 16.sp)
}
}

3. Inefficient Use of State

Using remember without mutableStateOf, so the value that should change or be updated is not updated. We can utilize mutableStateOf for state that will change, and can use viewModel if the state needs to persist outside of composable.

@Composable
fun Counter() {
val count = remember { 0 } // This will not change when the button is pressed

Button(onClick = { count++ }) {
Text("Count: $count")
}
}

Solution :

@Composable
fun Counter() {
val count = remember { mutableStateOf(0) }

Button(onClick = { count.value++ }) {
Text("Count: ${count.value}")
}
}

4. Not utilizing Lazy Componetns for Long Lists

Using Column for long lists, this will cause all items to be rendered at once. We can use LazyColumn, LazyRow or others to optimize perfomance on long lists

fun LongList() {
Column {
for (i in 1..1000) {
Text(“Item #$i”)
}
}
}

Solution :

@Composable
fun LongList() {
LazyColumn {
items(1000) { index ->
Text(“Item #$index”)
}
}
}

5. Improper use of Side

Using LaunchedEffect with Unit as dependency parameter when the process only needs to be done once, so the LaunchedEffect will be re-run continuously, we should use unique key or something like that if the process is only done once when the composition is first called.

@Composable
fun FetchData() {
LaunchedEffect(Unit) {
// Fetch data from API
}
}

Solution :

@Composable
fun FetchData(userId: String) {
LaunchedEffect(userId) {
// Fetch data from API with specified userId
}
}

Thank you for reading, hope you find it useful 🔥

--

--

HariAgusWidakdo
HariAgusWidakdo

Written by HariAgusWidakdo

Mobile Developer | Kotlin | SwiftUI 📱. Sometimes write my story 📚

No responses yet