Read more" />

๐Ÿ”‘ Avoid recompositions in Jetpack Compose with keys ๐Ÿ’ณ๐Ÿ“ˆ

When working with dynamic lists, like bank transactions, changes such as ๐—ฎ๐—ฑ๐—ฑ๐—ถ๐—ป๐—ด ๐˜๐—ผ ๐˜๐—ต๐—ฒ ๐˜๐—ผ๐—ฝ, ๐—ฟ๐—ฒ๐—ผ๐—ฟ๐—ฑ๐—ฒ๐—ฟ๐—ถ๐—ป๐—ด, ๐—ผ๐—ฟ ๐—ฟ๐—ฒ๐—บ๐—ผ๐˜ƒ๐—ถ๐—ป๐—ด ๐—ถ๐˜๐—ฒ๐—บ๐˜€ ๐—ฐ๐—ฎ๐—ป ๐˜๐—ฟ๐—ถ๐—ด๐—ด๐—ฒ๐—ฟ ๐˜‚๐—ป๐—ป๐—ฒ๐—ฐ๐—ฒ๐˜€๐˜€๐—ฎ๐—ฟ๐˜† ๐—ฟ๐—ฒ๐—ฐ๐—ผ๐—บ๐—ฝ๐—ผ๐˜€๐—ถ๐˜๐—ถ๐—ผ๐—ป๐˜€. This impacts performance and the user experience.

๐—จ๐˜€๐—ถ๐—ป๐—ด ๐—ธ๐—ฒ๐˜† allows Jetpack Compose to uniquely identify each item and preserve its state even when its position changes.

๐Ÿšฉ ๐—ง๐—ต๐—ฒ ๐—ฝ๐—ฟ๐—ผ๐—ฏ๐—น๐—ฒ๐—บ
Imagine a list of recent bank transactions:
– A new transaction is added at the top.
– An existing transaction is reordered.

Without optimisation, Compose will recompose every affected transaction, even if the data hasnโ€™t changed. This can waste resources and disrupt smooth animations or in-progress operations, such as fetching an image.

By wrapping each item in a key, Compose can uniquely identify it and retain its state even if its position changes. Find an example below.

๐Ÿš€ ๐—ช๐—ต๐˜† ๐˜๐—ต๐—ถ๐˜€ ๐˜„๐—ผ๐—ฟ๐—ธ๐˜€
๐Ÿ”ธ Preserves state: Each transaction is tied to its unique id, so Compose understands that the transaction itself hasnโ€™t changed, even if it moves in the list.
๐Ÿ”ธ Avoids interruptions: Side effects, like network calls or animations, wonโ€™t restart unnecessarily.
๐Ÿ”ธ Improves performance: Only the changed or added items are recomposed, reducing computational overhead.

๐Ÿ”ง ๐—ž๐—ฒ๐˜† ๐—ฝ๐—ผ๐—ถ๐—ป๐˜
Use the key composable to help Compose identify composable instances in the Composition. This is crucial when multiple composables are called from the same call site and involve side-effects or internal state.

Some composables, like ๐‘ณ๐’‚๐’›๐’š๐‘ช๐’๐’๐’–๐’Ž๐’, offer built-in support for keys. For instance, you can specify a custom key directly in the items DSL.

๐Ÿ”— ๐—ช๐—ต๐˜† ๐—ถ๐˜ ๐—บ๐—ฎ๐˜๐˜๐—ฒ๐—ฟ๐˜€
Efficient recomposition ensures smoother experiences, especially for dynamic and complex UIs like transaction lists in banking apps. By leveraging key, we align with Jetpack Compose’s optimised lifecycle management.

๐Ÿ‘‰ Link to official documentation here.

optimize recompositions jetpack compose

Call today

+34 634 548 126

You've found the person you were looking for. Let's talk.

Let's get you started