26. Lists & Keys
Rendering Arrays of Data
Very rarely will you hardcode all the text on a website. Instead, you fetch an array of data (like a list of products, tweets, or users) from a database, and you want to generate a React component for every single item in that array. We do this using the JavaScript .map() array method.
Using the .map() Method
The .map() method takes an array, applies a function to every item, and returns a completely new array. In React, we use it to transform an array of raw data into an array of JSX elements.
The Crucial "key" Prop
Notice the key={user.id} in the code above. When rendering lists in React, you must provide a unique key prop to the top-level element being returned by the map function.
React uses a highly optimized "Diffing Algorithm" to figure out what changed in the UI. If the list changes (e.g., a user is deleted, or the list is sorted alphabetically), React uses the keys to identify exactly which specific item moved or was removed. Without keys, React gets confused, destroys the whole list, and redraws it from scratch (terrible performance), or worse, assigns data to the wrong elements (UI bugs).
Why You Shouldn't Use the Array Index as a Key
If your data doesn't have an ID, you might be tempted to use the map's index (0, 1, 2...). Avoid this if the list can be modified. If you delete the item at index 0, the item at index 1 shifts to index 0. React's keys didn't change, but the data shifted underneath them, causing massive rendering bugs. Always use a unique database ID.
Knowledge Check
Ready to test your understanding of 26. Lists & Keys?