The following code snippet attempts to render a list of items. Identify the potential performance issues and provide a corrected version.

React JS interview question for Advanced practice.

Answer

The primary issue is the use of the array index as the key prop. Using the index as a key is generally discouraged because it can lead to performance issues and bugs when the list is modified (e.g., items are added, removed, or reordered). React uses the key to track the identity of an element across renders. If you use the index, and an item is added to the beginning of the list, React will see that every following item's key has changed and may perform unnecessary re-renders and state updates for the entire list. A more robust solution involves using a unique and stable identifier from the data itself as the key. Corrected Code: Assuming each item has a unique id property, the corrected code would be: jsx const MyComponent = ({ items }) = ( <ul {items.map((item) = ( <li key={item.id} {item.name} </li ))} </ul ); If the items do not have a unique ID, it's best practice to generate one when the data is created, rather than relying on the index during rendering.

Explanation

Using the array index as a key is an anti-pattern if the list's order can change, as it can lead to inefficient updates and bugs with component state.

Related Questions