![]() |
VOOZH | about |
A key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list.
When rendering a list, you need to assign a unique key prop to each element in the list. This helps React identify which elements have changed, been added, or been removed.
Syntax
const numbers = [1, 2, 3, 4, 5];
const updatedNums = numbers.map((number, index) =>
<li key={index}>
{number}
</li>
);
While React allows you to use the index of an array as a key, it is highly discouraged in most scenarios. Hereβs why:
When extracting list items into separate components, assign the key to the component rather than the individual list items. This ensures that React can track changes to the component as a whole.
Output
Output
Itβs Important that keys assigned to the array elements are unique within the list. However, keys do not need to be globally unique, only unique within a specific array. This means that two different arrays can have the same set of keys without issues.
Output
Props | Keys |
|---|---|
Used to pass data from parent to child components. | Used to uniquely identify elements in a list or collection. |
Props can be accessed within the component. | Keys are internal to React and cannot be accessed within the component. |
Passed into a component as data for rendering or behavior. | Assigned to elements (e.g., list items) to track them across renders. |
Props are passed and can be reused within the component. | Keys should be unique within the list but can be the same across different lists. |
Props define component behavior and data. | Keys help React optimize re-renders and track changes efficiently. |