Is your Jetpack Compose app lagging during scrolls? The culprit might be your State management. 🧵👇
When you have a state that changes frequently (like a scroll position or a timer) and you use it to calculate a new value, Compose might be doing way more work than necessary.
📉 The Problem: Excessive Recomposition
If you calculate a boolean like val showButton = listState.firstVisibleItemIndex > 0 directly in your Composable, that line will trigger a recomposition every single time the user scrolls even one pixel. Your UI thread will be fighting for its life!
✅ The Solution: derivedStateOf
By wrapping that logic in derivedStateOf, you tell Compose: "Only notify me when the result of this calculation changes, not when the input changes."
The "Mint" Tip: Think of derivedStateOf as a buffer. In the example below, the button only recomposes once (when the index hits 1) instead of hundreds of times during the scroll.
// ❌ BAD: Recomposes on every pixel scrolled
val showButton = listState.firstVisibleItemIndex > 0
// ✅ GOOD: Only recomposes when the Boolean actually flips
val showButton by remember {
derivedStateOf {
listState.firstVisibleItemIndex > 0
}
}
if (showButton) {
FloatingActionButton(onClick = { /* Scroll to top */ })
}
🚀 Why this matters:
Battery Life: Less CPU work = longer battery for your users.
Jank-Free UI: Keeps your animations at a buttery-smooth 120Hz.
Scalability: Essential for complex screens with many moving parts.
Have you checked your Layout Inspector lately to see how many recompositions your scroll logic is triggering? Let's discuss in the comments! 👇
#JetpackCompose #AndroidDev #Kotlin #CleanCode #AndroidPerformance #MobileDevelopment