What is a key in React ?

A “key” is a special string attribute you need to include when creating lists of elements in React. Keys are used in React to identify which items in the list are changed, updated, or deleted.

Keys are used to give an identity to the elements in the lists. It is recommended to use a string as a key that uniquely identifies the items in the list.  

ReactJS Keys

React JS keys are a way of providing a unique identity to each item while creating the React JS Lists so that React can identify the element to be processed.

Table of Content

  • What is a key in React ?
  • Assigning keys to the list
  • Issue with index as keys
  • Difference between keys and props in React
  • Using Keys with Components
  • Incorrect usage of keys
  • Correct usage of keys
  • Uniqueness of Keys

Similar Reads

What is a key in React ?

A “key” is a special string attribute you need to include when creating lists of elements in React. Keys are used in React to identify which items in the list are changed, updated, or deleted....

Assigning keys to the list

You can assign the array indexes as keys to the list items. The below example assigns array indexes as keys to the elements....

Issue with index as keys

Assigning indexes as keys is highly discouraged because if the elements of the arrays get reordered in the future then it will get confusing for the developer as the keys for the elements will also change....

Difference between keys and props in React

Keys are not the same as props, only the method of assigning “key” to a component is the same as that of props. Keys are internal to React and can not be accessed from inside of the component like props. Therefore, we can use the same value we have assigned to the Key for any other prop we are passing to the Component....

Using Keys with Components :

Consider a situation where you have created a separate component for list items and you are extracting list items from that component. In that case, you will have to assign keys to the component you are returning from the iterator and not to the list items. That is you should assign keys to and not to

  • A good practice to avoid mistakes is to keep in mind that anything you are returning from inside of the map() function is needed to be assigned a key....

  • Incorrect usage of keys:

    Example 1: The below code shows the incorrect usage of keys:...

    Correct usage of keys:

    ...

    Uniqueness of Keys:

    Example 2: The below example shows the correct usage of keys....

    Contact Us