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.