ReactJS Tutorial – 19 – Index as Key Anti-pattern
![*](https://i0.wp.com/allprowebdesigns.com/wp-content/uploads/2023/12/1703719210_maxresdefault.jpg?resize=840%2C430&ssl=1)
Video Title: ReactJS Tutorial – 19 – Index as Key Anti-pattern
When reading articles are going through react tutorials you’re often going to see a lot of examples where developers use the index of an element as the key for list rendering it keeps the code simple and elegant and of course gets rid of the warning you see in the
Console in this video I want to show you how to use the index as a key when rendering lists and also the problems you might face when used in the wrong scenario I’m going to go back to vs code and in the name list component I am
Going to add back the names array cons names is equal to an array of strings Bruce Clark and Diana let’s render this list of names instead of the person’s array Const name list is equal to names dot map and the map method takes in an arrow function let’s call the parameter
As name which represents the Eric item in each iteration within the function body let’s return + h2 tag with the name as inner text and the name list component now returns name list instead of person list if you save the file and take a look at the
Browser you can see that we are rendering the list of names if we open the console we of course have the error but we do know how to fix this error we need to add the key prop there is one problem though which we did not have
Before we don’t have an ID that uniquely identifies each item in the array we could use the name itself as the key so in the map method on the h2 element the key prop and this is going to be equal to name if I save the file now and take
A look at the browser you can see that the error is gone but what if there is duplication of names let’s add Bruce again to the end of the list now the name is not unique anymore and if you remember from the warning the
Key prop has to be unique if you take a look at the browser you should be able to see a new warning encountered two children with the same key Bruce well it turns out the arrow function that is passed to the map method receives a second parameter which is the
Index of the element in the current iteration let me show that to you the arrow function will now accept two parameters so we need parenthesis name and index we can now use this index as the key when rendering the list so ki is equal to index
Let me also display the index so as to get a better picture of how it works if you now save the file and take a look at the browser you can see the list displayed along with the index you can see that the index starts at zero and
Keeps incrementing for every element in the array and that way every item receives a unique key value so this is how you can use the index value as a key for list rendering the index is passed as a second parameter to the error function within the map method and that
Index is used as a value to the key prop let me tell you though using the index as a key will cause some serious UI issues in certain scenarios and to demonstrate such scenarios I have modified a code an example from the react dots the link will be in the
Description at the very top we have four buttons add a new item to the start of the list add a new item to the end of the list sort the list by earliest create a date and finally sort by latest created date below that we have a table
With the headings index which specifies the position of the item in the list and IB which is self incrementing item which is an input where we can enter a value and they created at timestamp on the list we are using the map operator the arrow function accepts two
Parameters to do which represents the item in iteration and the index of the item in the list the same index is used as a value to the key attribute for rendering the list now back in the UI for the first item I am going to add a
Value of 1 next I’m going to add a new item to the end of the list you can see that a new row is inserted into the list the index is now 1 ID is incremented to to the timestamp is also present let me add a value of 2 similarly if I add
Another item to the end of the list we see the same behavior everything works as expected now what should happen if I add a new item to the start of the list for the new item I would expect the index to be 0 because it is at the beginning the ID
However should be incremented so it should be for the value should be empty and there should be a new timestamp pay real close attention when I click on add new to start you can see that a new row is inserted but it doesn’t quite work as
We expected it to we expected index to be 0 so that works we expected ID to be incremented to 4 so that works as well the timestamp is new so that also works but we expected the value to be blank or empty instead it has a value of 1 and
The last item in the list which previously had a value of 3 is now empty this is the problem of using the key as index let me show you how react interprets the update initially we have the three items with the index as keys for key zero there is
A value of 1 for key 1 there is a value of 2 and similarly for key too there is a value of 3 now when you insert a new item at the beginning the new item gets an index of 0 which effectively creates a key with a
Value of 0 and that pushes the key value by 1 for the remaining elements when updating the UI react thinks that hey I already have the three elements with key equal to zero one and two let me reuse them and then insert that new item with key value of four oh and
As it turns out the first three items had some values let me put them back this says how even though we inserted a new item at the top it appears as though it was inserted at the bottom and the values are all messed up and this is
Also the problem when trying to sort the list if I go back to code Bend and refresh we should have a single item I will add two more items to the end of the list so three items with value of one two and three each of them with different time
Stamps if I click on sword buy earliest the timestamp should be in ascending order and you can see that the list is sorted when I click on sword buy latest the timestamp is in descending order but item values don’t seem to be in the right order irrespective of me sorting
By earliest or latest the item values never change this again is because of using the index as key when rendering the list now you might have a question if using the index as key results in such issues why do so many articles or videos do that well it
Turns out you can use the index as a key provided your list satisfies certain conditions the first condition is that the items in your list do not have a unique ID if the items do have a unique ID always go with that the second condition is that the list is a static
List and will not change for example you are never adding items to the list or removing items from the list finally the list will never be reordered or filter for example sorting based on a column value or filtering based on user inputs when your list satisfies not just one
But all the three conditions you can safely use the index as a key most of the times you end up having a unique ID or the list will be satisfying the three conditions if not you can try one of the NPM packages that generate a unique ID for a
List or also try hashing out a unique value from one of the existing properties but the bottom line is try avoiding the use of index as a key and let that be your last resort in fact react uses the index as the key if at all you don’t specify the key prob and
Of course we have just learned how that can be a disaster in certain scenarios all right I hope you now have a good understanding of lists and keys in react thank you guys for watching feel free to subscribe I’ll see you guys in the next video
-
Sale!
Wireless WIFI Repeater Extender Amplifier Booster 300Mbps
$29.99$14.99 Add to cartWireless WIFI Repeater Extender Amplifier Booster 300Mbps
Categories: Electronics, Wi-Fi Router, Wireless Wi-Fi Extender Tags: 300Mbps, 802.11N, Amplifier, Booster, Extender, mobile wi-fi booster, Remote, WIFI, Wireless, Wireless WIFI, Wireless WIFI Repeater, Wireless WIFI Repeater Extender, Wireless WIFI Repeater Extender Amplifier, Wireless WIFI Repeater Extender Amplifier Booster, Wireless WIFI Repeater Extender Amplifier Booster 300Mbps$29.99$14.99 -
Sale!
Full RGB Light Design Gaming Headset Headphones with Mic
$24.99$14.99 Add to cartFull RGB Light Design Gaming Headset Headphones with Mic
Categories: Electronics, Gaming, Gaming Headsets Tags: Design, Full, Full RGB Light Design Gaming Headset, Full RGB Light Design Gaming Headset Headphones, Full RGB Light Design Gaming Headset Headphones with Mic, Gamer, Gaming, Gaming Headset Headphones, gaming headset wireless, Headphone, Headphones, Headset, Light, Mic, Package, RGB$24.99$14.99 -
Sale!
Wireless BlueTooth Multi-Device Keyboard Mouse Combo
$39.99$19.99 Add to cartWireless BlueTooth Multi-Device Keyboard Mouse Combo
Categories: Electronics, Gaming, Gaming Keyboards, Keyboard Mouse Combos Tags: Combo, Keyboard, keyboard mouse combos, Mouse, MultiDevice, Set, WireKeyboard Mouse Combo, Wireless, Wireless BlueTooth Keyboard Mouse Combo, Wireless BlueTooth Keyboard Mouse Combos, Wireless BlueTooth Multi-Device Keyboard Mouse Combo, Wireless BlueTooth Multi-Device Keyboard Mouse Combos$39.99$19.99 -
Sale!
High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
$199.99$139.99 Add to cartHigh Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
Categories: Gaming, Gaming Chairs Tags: Adjustable, Chair, computer chairs, Desk, Executive, Gaming, Girl, Headrest, High, High Back Leather Executive Adjustable Swivel Gaming Chair, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar, High Back Leather Executive Adjustable Swivel Gaming Chairs, Leather, Lumbar, Office, Racing, Swivel$199.99$139.99 -
Sale!
Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
$29.99$19.99 Select optionsProfessional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
SKU: N/A Categories: Electronics, Gaming, Gaming Headsets Tags: Cancelling, Gaming, Gaming Headphones with Noise Cancelling Microphone, gaming headset, Headphones, Headset, LED, Light, Mic, Microphone, Noise, Professional, Professional LED Light Wired Gaming Headphones, Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone, Wired, Wired Gaming Headphones, Wired Gaming Headphones with Noise Cancelling Microphone$29.99$19.99 -
Sale!
Gaming Desk with LED Lights USB Power Outlets and Charging Ports
$349.99$249.99 Select optionsGaming Desk with LED Lights USB Power Outlets and Charging Ports
SKU: N/A Categories: Computer Desk, Gaming, Gaming Desk Tags: and Charging Ports, Charging, Desk, Desks, Gaming, gaming desk with led lights, Gaming Desks with LED Lights, Home, LED, Lights, Monitor, Office, Outlets, Port, Power, Room, Stand, USB, USB Power Outlets, White, Workstation$349.99$249.99 -
Sale!
Wired Mixed Backlit Anti-Ghosting Gaming Keyboard
$99.99$79.99 Add to cartWired Mixed Backlit Anti-Ghosting Gaming Keyboard
Categories: Electronics, Gaming, Gaming Keyboards Tags: Antighosting, Backlit, Blue, brown, Gaming, Gaming Keyboard, gaming keyboards, gaming keyboards and mouse, Keyboard, Laptop, Switch, Wired, Wired Mixed Backlit Anti-Ghosting Gaming Keyboard, Wired Mixed Backlit Anti-Ghosting Gaming Keyboards, Wired Mixed Backlit Gaming Keyboard$99.99$79.99 -
Sale!
Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
$119.99$59.99 Add to cartWireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
Categories: Electronics, Gaming, Gaming Headsets Tags: 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, ANC, Audio, Bluetooth, Cancellation, Ear, Earphone, gaming headset, Headphones, Headset, Hi-Res Over the Ear Headphones Headset, HiRes, Noise, Wireless, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Headphones, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headsets$119.99$59.99 -
Sale!
Wired Sports Gaming Headset Earbuds with Microphone
$19.99$9.99 Select optionsWired Sports Gaming Headset Earbuds with Microphone
SKU: N/A Categories: Gaming, Gaming Headsets Tags: Accessories, Earbud, Earphone, Earphones, Gaming, gaming headset with microphone, Headphones, Headset, IOS, Microphone, Sports, Wired, Wired Sports Gaming Headset Earbuds, Wired Sports Gaming Headset Earbuds with Microphone, Wired Sports Headset Earbuds$19.99$9.99 -
Sale!
150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
$49.99$29.99 Add to cart150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
Categories: Charging Stations, Electronics Tags: 150W, 150W Charging Station, 150W Universal Multi USB Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Stations, 150W Universal Multi USB MAX Charging Station, 16 Port MAX Charging Station, 3.5A, Charger, Charging, Fast, laptop charging stations, Max, Multi, Port, Stand, Station, Universal, USB$49.99$29.99
Why weren't Index, ID, and Created at not get messed up too like Item ? I thought they were all part of ToDo?
completed video 19. Thanks 🙂
Thank you for speaking slowly and clearly so that we can follow every word!
Hi sir. In this case, I can understand Key is not changed. But will that be an issue as 'Key' prop is used by React alone right and anyways we will not able to use that prop and hence do we still need to worry on it? Can we use index as key till we are not rely on key property for anything? Please advise. Thanks in advance.
🗝 The "key" prop in React is essential for rendering lists efficiently. It should have a unique value within the list.
🗝 The "key" prop value can be any unique identifier within the list, such as ID or name, but it should not be accessed or used in child components.
🔄 React uses keys to efficiently update the UI when items are added, removed, or changed within a list.
🗝 If your data doesn't have a unique identifier, you can use index as the key, but it's less efficient and should be a last resort.
the odin project
Thank you
As prophet Muhammad (PBUH) said those who don't thanks people don't thank God, really thank you for such a wonderful course.👍🌼
6:50 * this is the problem of using the index as key * 😉
just amazing course!! Why didnt i found thiscourse early.🤦♂🤦♂
but , what is the solution if we using index as key and list will need to be sorted ?
Wow, You explained it so well, Thank You!
Thank you so much.
Thank you. You are a true champ indeed.
Actually i am the begginer of react and i want know how you implement the project of in this video
You confused me
man u confused me in last video and this one also. how i will pass index to Persons u skiped that part. 😕😕😠
7:03 that is incorrect explaination for the codepen, react doc mentions the component state in the uncontrolled input is the reason. Without that state, the element will add to the top just fine with index as key, it only causes more updating to the DOM node
key prop for normal arrays – can be its 'index'. But it has disadvantages. so don't use use index.
did not understand why dorting doesnot sort actual values but index
3:00 second param of map function
awesome explanation 🙏
Making a calculator,
Just realized how important this video is😅
Thanks dude!
7:00 index as key anti-pattern
2:44 arrow function was passed to map method, then arrow function receives a 2nd param which is the index of the element in current iteration.
Thankyou sir
👍
for me it´s too hard to understand the indian accent
good explanation, thanks
Very Helpful Video
Bruce Wayne, Clark Kent, Diana Prince ?
If I remove the input box and replace it with a span with id as text, then I cannot simulate this behavior. Guess it only happens when you have an uncontrolled component in ur siblings.
Thank you once again!
4:54 Requesting more explanation for better understanding
What if the supported array doesn't have an unique ones(id or something), and we also need to filter or order that array too?
What is the use of three periods before todo and before the array of list while adding new element
Why do the id and timestamp values still maintain the correct placement? – what links them that doesn't link the inputted value