Skip to content

Commit 485f149

Browse files
committed
Added details and codepen examples for index usage as keys in lists
1 parent 1871cea commit 485f149

File tree

2 files changed

+6
-2
lines changed

2 files changed

+6
-2
lines changed

content/docs/lists-and-keys.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ const todoItems = todos.map((todo, index) =>
130130
);
131131
```
132132

133-
We don't recommend using indexes for keys if the items can reorder, as that would be slow. You may read an [in-depth explanation about why keys are necessary](/docs/reconciliation.html#recursing-on-children) if you're interested.
133+
We don't recommend using indexes for keys if the items can reorder as that would impact performance, and may cause issues with the reordering of components and their respective states. If you choose not to assign a key to your list items then React will use indexes as keys. You may read an [in-depth explanation about why keys are necessary](/react/docs/reconciliation.html#recursing-on-children) if you're interested in more information.
134134

135135
### Extracting Components with Keys
136136

content/docs/reconciliation.md

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,11 @@ In practice, finding a key is usually not hard. The element you are going to dis
138138

139139
When that's not the case, you can add a new ID property to your model or hash some parts of the content to generate a key. The key only has to be unique among its siblings, not globally unique.
140140

141-
As a last resort, you can pass item's index in the array as a key. This can work well if the items are never reordered, but reorders will be slow.
141+
As a last resort, you can pass item's index in the array as a key. This can work well if the items are never reordered. However, there will be a performance impact with reordering as React will naively update components.
142+
143+
There can also be issues with the state of a component in a list if indexes are used as keys. The state of an item in a list (or any deep state inside of it) will stay attached to the original position of the item, even if the item has “moved” in the data source. This is particularly noticeable with inputs retaining their values in the original positions even when their parent components reorder or are prepended to.
144+
145+
[Here](http://codepen.io/ajcumine/pen/KmVWmQ?editors=0010) is an example of the issues that can be caused by using indexes as keys on CodePen, and [here](https://codepen.io/ajcumine/pen/ZKQeJM?editors=0010) is a updated version of the same example showing how not using indexes as keys will fix these reordering, sorting, and prepending issues.
142146

143147
## Tradeoffs
144148

0 commit comments

Comments
 (0)