1
00:00:00,000 --> 00:00:03,100
In my React list, I check

2
00:00:03,100 --> 00:00:06,000
pizza and sort the rows.

3
00:00:06,000 --> 00:00:07,705
Now salad is checked.

4
00:00:07,705 --> 00:00:09,840
Who changed my lunch?

5
00:00:10,020 --> 00:00:15,000
Your keys are array indexes: zero and one.

6
00:00:15,000 --> 00:00:18,190
After sorting, key zero still exists,

7
00:00:18,190 --> 00:00:20,000
but now it shows salad.

8
00:00:20,000 --> 00:00:23,780
React keeps that row component and its checked state.

9
00:00:23,960 --> 00:00:28,030
So the checkbox did not follow the food.

10
00:00:28,030 --> 00:00:29,950
The first row kept its state

11
00:00:29,950 --> 00:00:31,880
and got a different label?

12
00:00:32,060 --> 00:00:33,000
Exactly.

13
00:00:33,000 --> 00:00:36,000
This row owns checked in useState.

14
00:00:36,000 --> 00:00:40,000
A new item prop does not reset that state.

15
00:00:40,000 --> 00:00:42,000
With index keys, the same position

16
00:00:42,000 --> 00:00:44,580
can represent a different item.

17
00:00:44,760 --> 00:00:48,000
Use a stable ID from the item instead.

18
00:00:48,000 --> 00:00:52,000
Now React matches the pizza row with pizza after sorting.

19
00:00:52,000 --> 00:00:54,520
Its checked state moves with it.

20
00:00:54,700 --> 00:00:58,000
Do not create random keys during rendering.

21
00:00:58,000 --> 00:01:02,000
New keys create new rows and reset state.

22
00:01:02,000 --> 00:01:05,110
Index keys can fit a fixed list

23
00:01:05,110 --> 00:01:07,580
whose items never change position or identity.

24
00:01:07,760 --> 00:01:13,000
My app changed my lunch without asking.

25
00:01:13,000 --> 00:01:15,600
Even my bugs think I should eat a salad.
