What is "key" prop and what is the benefit of using it in arrays of elements?

DWQA QuestionsCategory: Web Design HTMLWhat is "key" prop and what is the benefit of using it in arrays of elements?
Editor Staff asked 2 weeks ago

What is “key” prop and what is the benefit of using it in arrays of elements?

1 Answers
Editor Staff answered 2 weeks ago

key is a special string attribute you should include when creating arrays of elements. Key prop helps React identify which items have changed, are added, or are removed.
Most often we use ID from our data as key:

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>
)