What is Key and benefit of using it in lists?

Technology CommunityCategory: ReactWhat is Key and benefit of using it in lists?
VietMX Staff asked 3 years ago

key is a special string attribute you need to include when creating lists of elements. Keys help React identify which items have changed, are added, or are removed.

For example, most often we use IDs from your data as keys

const todoItems = todos.map((todo) =>
    <li key={todo.id}>
    {todo.text}
    </li>
);

When you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort:

const todoItems = todos.map((todo, index) =>
    <li key={index}>
        {todo.text}
    </li>
);

Note:

  1. We don’t recommend using indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state
  2. If you extract list item as separate component then apply keys on list component instead li tag.

There will be a warning in the console if the key is not present on list items.