Component Keys (Spec API)
This page documents the legacy Spec API approach to setting manual keys. For the modern Kotlin API approach, see Maintaining Component Identity with Keys.
Keys help Litho to set a unique identity on a component that represents a node in the component tree. Litho uses keys to keep track of component identity between layout changes and correctly identify a component as the target of a state update.
Assigning manual keys in Spec API
For dynamic UI hierarchies where components can change position, manual keys that are stable between UI updates must be assigned to components. The manual key will always take precedence over the autogenerated one.
In the Spec API, the common key component prop can be used to manually set a key when a component is created:
Row.create(c)
.key("first_row")
.child(CounterComponent.create(c))
.child(
Text.create(c)
.text("X")
.paddingPx(YogaEdge.START, 16)
.clickHandler(IdentityRootComponent.onClickRemoveFirstChild(c)))
Setting manual keys is also a nifty way to force a component's state value to be initialised again based on the value of certain props for example, if the manual key is a function of those props.