What are "key" props and what are they used for in arrays of elements in REACT?

Practice



A

key
is a special string attribute that you must include when creating arrays of elements. Keys help React determine which items have been changed, added or removed.

Most often we use identifiers from our data as keys :

const todoItems = todos.map((todo) =>
  <li key={todo.id}>
    {todo.text}
  </li>
)
If you don't have stable identifiers for the items being rendered, you can use the item's index as the key as a last resort:
const  todoItems  =  todos . map (( todo , index ) => < li  key = { index } > { todo . text } </ li > )

Notes:
  1. Using indexes for keys is not recommended if the order of the items may change. It can hurt performance and may cause problems with component state.
  2. If you extract a list item as a separate component, then apply the keys to the list component instead of the
    li
    tag.
  3. A warning message will appear in the console if the
    key
    prop is missing from list items.
created: 2020-02-23
updated: 2026-03-08
224



Was this answer useful?
Choose a quick rating so we can improve the next answer for you.
How satisfied are you?


Comments

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "Scripting client side JavaScript, jqvery, BackBone"

Terms: Scripting client side JavaScript, jqvery, BackBone