So, showing the list of items is common in many applications. Sometimes when we scroll through the list we feel the laggy behaviour and it’s too bad for UX. In Jetpack Compose we use LazyColumn to show the items Verticaly and LazyRow to show items Horizontally.
While using LazyColumn to show items we face some laggy behaviour, so let's learn how can we fix that laggy behaviour and make the LazyColumn as smooth as possible.
1. Try to test it on release mode
Don’t worry if your app is laggy in debugging. It’s completely fine. Just create the APK in release mode (Build -> Generated Signed Bundle/APK), which might solve your problem. This happens because when in debugging, Compose translates bytecode in runtime using JIT, and make sure you have R8 compiler enabled and use precompiled binary/baseline profile.
2. Set a key for your items
So, what does this key parameter do, so the key composable allows the compose compiler to identify each composable as distinct and eliminate the wasteful recompositions. The key must be unique to the list otherwise it will crash.
This works almost like DiffUtil work in RecyclerView in XML and we know how much improvement is increased in performance of RecyclerView get with DiffUtil.
3. Use remember{ } block
The remember block in Jetpack Compose ensures that the state variable persists across recompositions, preventing unnecessary recompositions and preserving the state during configuration changes. This is crucial for optimizing performance and maintaining a consistent user interface, especially when dealing with expensive operations or fetching data, as it avoids redundant computations and network calls on each recomposition.
In this easy example, remember is used to store the list of items, ensuring that it remains unchanged during recompositions of the LazyColumn. This helps optimize performance by preventing unnecessary recomputations of the item list on each UI redraw. The generateItems function simulates a list of strings for demonstration purposes.
4. Use lightweight/compressed images in LazyColumn
Lag issues in LazyColumn are often attributed to the use of heavy images, making it imperative to choose images that are optimized for quick rendering. While addressing this concern, incorporating image caching libraries such as Coil can be a valuable strategy. These libraries efficiently manage the loading and caching of images, contributing to a smoother user experience.
5. Use @Stabe and @Immutable on data class
The annotations @Stable and @Immutable are used to tell compose that the data class is stable and it will not change.
So, by adding these annotations you can tell compose that the data class is stable, but the most important point is it doesn’t make any class Stable/Immutable on it own. Incorrect annotating a class could cause recomposition.
Top comments (0)