when we should use key() is there like some guide ...
# compose
m
when we should use key() is there like some guide to that?
1
j
If your widgets are stateless because you are properly utilizing state hoisting (https://developer.android.com/jetpack/compose/state#stateless-composables) then you shouldn't need to use
key
. Otherwise, if you fail to hoist your state, then
key
is needed when you emit widgets within a
for
loop (directly or indirectly). In such a case, you need to use
key
to tell Compose the identity of each widget, so the state of the widget can be correctly associated with the intended widget on screen. Otherwise, state may be accidentally transferred to the wrong widget. React.js has a similar concept of keys, and this jsfiddle demonstrates the state transference problem pretty well: http://jsfiddle.net/frosas/S4Dju/ If your widget state is not hoisted, then within every loop, you will need to wrap each widget in a
key
and pass in a unique identifier for that widget (an ID for example). For example, if I had a bookstore, I would use the ISBN number as the key for each book.
Copy code
for(book in books) {
   key(book.isbn) {
      Box(...) {
         ...
         Text(book.title)
         Text(book.description)
         ...
      }
   }
}
👍 2
m
If a composable uses animation then its not statless right? Then we should use key?
j
Correct, or make it possible to hoist the animation. There is a strategy known as "BlackBoxState" where the state of a widget (including animation) is hoistable but some or all of the values are "black box" (that is, unavailable to the parent).
Copy code
class MyWidgetBlackBoxState {
   internal var animationSpring = ...
}

@Composable
fun MyWidget(state: MyWidgetBlackBoxState = MyWidgetBlackBoxState()) {
  ...
}
By making the state hoistable in this way, it opens a bunch of options (like reparenting, allowing a parent to control the animation, allowing for the coordination of the animation with other animations, etc) which makes it a generally nice practice.
👍 1
a
to give an example, i had to use it in order to get animations working in a 2048 game i created using jetpack compose https://github.com/alexjlockwood/android-2048-compose/blob/master/app/src/main/java/com/alexjlockwood/twentyfortyeight/ui/GameGrid.kt#L80
👍 1