# Keys

> What keys mean for diffing, identity and preserving DOM references across updates.

Source: https://haskell-miso.org/docs/keys/

A `Key` is a unique identifier used to optimise diffing. Virtual DOM nodes can be keyed with `key_`. Keys have multiple meanings in miso (as in React).

## Keys optimise child-list diffing

When two lists of elements are diffed and all of them have unique keys, diffing large child lists is much faster. This optimisation fires automatically when *all* elements in a child list carry unique keys — unless every node in the list is keyed, it will not.

## Keys compare two identical nodes

If two `VNode`s (or two `VComp`s) are being compared and their keys differ, the old node is destroyed and a new one created. Otherwise the underlying DOM node is kept and its properties diffed. For components, differing keys trigger the `unmount` phase for the old component and the `mount` phase for the new one; the DOM reference is replaced.

## Keys preserve the DOM reference

Because a stable key keeps the same DOM node in place, CSS animations on that node are not interrupted by re-renders. Without a key diffing may recreate the node, resetting any in-progress animation. Assigning a stable key to an animated element guarantees the animation runs to completion.

## Usage

See the `key_` property, and smart constructors like `textKey_`, `vfrag_` and `(+>)`:

```haskell
H.ul_ []
  [ H.li_ [ key_ "key-1" ] [ "a" ]
  , H.li_ [ key_ "key-2" ] [ "b" ]
  , "key-3" +> counter
  , textKey "key-4" "text here"
  , vfrag_ "key-5" [ "foo", "bar" ]
  ]
```
