In Jetpack Compose, UI can recompose too often if the state is not handled right. That makes the app slow or unpredictable. Below are common recomposition bugs and how to fix each one with a real example.
1. Function Runs Again and Again
If you call a function inside a Composable, it runs every time the UI redraws.
@Composable
fun UserCard() {
val user = getUserFromRepo() // runs every recomposition
Text(text = user.name)
}
Fix: Use remember
to cache the result.
val user = remember { getUserFromRepo() }
This way, the function only runs once unless inputs change.
2. Input Triggers Recomposition Too Much
Let’s say you check if an input is valid.
val isValid = inputText.length > 5
This runs every time the user types. Even when the result is the same.
Fix: Use derivedStateOf
with remember
.
val isValid = remember(inputText) {
derivedStateOf { inputText.length > 5 }
}
This prevents recomposition unless the result changes.
3. Toast Keeps Showing Again
Showing a Toast or a log message inside a Composable without care causes repeats.
@Composable
fun WelcomeMessage() {
Toast.makeText(context, "Hello", Toast.LENGTH_SHORT).show()
}
This shows the Toast every time the Composable recomposes.
Fix: Wrap it inside LaunchedEffect
.
@Composable
fun WelcomeMessage() {
val context = LocalContext.current
LaunchedEffect(Unit) {
Toast.makeText(context, "Hello", Toast.LENGTH_SHORT).show()
}
}
Now the side effect only runs once.
4. LazyColumn Items Recompose or Jump
List items may reset or jump if Compose can’t track their identity.
LazyColumn {
items(users) { user ->
UserRow(user)
}
}
Fix: Add a stable key using item ID.
LazyColumn {
items(users, key = { it.id }) { user ->
UserRow(user)
}
}
This keeps each item stable and prevents redraws.
Final Notes
To fix recomposition issues in Jetpack Compose:
- Use
remember
to keep values from re-running - Use
derivedStateOf
for clean recompute logic - Use
LaunchedEffect
for one-time side effects - Use keys in
LazyColumn
to avoid jumps
These small changes help keep your UI fast and clean.
No comments:
Post a Comment
Share your thoughts ...