diff --git a/curriculum/challenges/english/blocks/lecture-working-with-data-in-react/673500b41af8500191febedc.md b/curriculum/challenges/english/blocks/lecture-working-with-data-in-react/673500b41af8500191febedc.md index 9f4535a0f71..3805356ebca 100644 --- a/curriculum/challenges/english/blocks/lecture-working-with-data-in-react/673500b41af8500191febedc.md +++ b/curriculum/challenges/english/blocks/lecture-working-with-data-in-react/673500b41af8500191febedc.md @@ -24,7 +24,21 @@ function FruitList() { In this example, the `map` function iterates over each item in the `fruits` array. For each fruit, it creates a new `li` element containing the fruit's name. The newly created array of `li` elements is then displayed inside the `ul` parent tags. -However, when rendering lists in React, it is important not to forget the `key` prop for each element in the list. The key must always be unique and it helps React identify which items have changed, been added, or been removed, which is essential for efficient rendering and updating the list. +However, when rendering lists in React, it is important not to forget the `key` prop for each element in the list. The key must always be unique and it helps React identify which items have changed, been added, or been removed, which is essential for efficient rendering and updating the list. + +If you forget the key, React will show a warning in the console, but it will not throw a fatal error. The application might still render and function, but you may encounter subtle bugs, especially when the list changes. These bugs can be difficult to debug because the UI might look correct initially. + +A common mistake is to use the array index as the key, like this: + +```jsx +{fruits.map((fruit, index) =>
  • {fruit}
  • )} +``` + +While this silences the warning, it is generally considered an anti-pattern. Using the index as a key can cause issues when the list is reordered, sorted, or filtered. React uses the key to track elements. If the list order changes, React might incorrectly reuse component state or fail to update the DOM efficiently because the keys (indexes) stay the same even if the content at that index has changed. + +The best practice is to use a stable, unique identifier for each item. This is typically an ID from your database, like a UUID or a database ID. + +If your data doesn't have a unique ID, you can generate one when the data is created (e.g., using `crypto.randomUUID()` or a library like `uuid`), or use a combination of fields that are guaranteed to be unique. However, you should avoid generating keys on the fly during rendering (e.g., `key={Math.random()}`), as this will cause React to recreate the DOM elements on every render and reset their state. Let's modify our example to include keys: