React Keys

 

A key is a unique identifier. In React, it is used to identify which items have changed, updated, or deleted from the Lists. It is useful when we dynamically created components or when the users alter the lists. It also helps to determine which components in a collection needs to be re-rendered instead of re-rendering the entire set of components every time.

Keys should be given inside the array to give the elements a stable identity. The best way to pick a key as a string that uniquely identifies the items in the list. It can be understood with the below example.

Example

 
  1. const stringLists = [ ‘Peter’‘Sachin’‘Kevin’‘Dhoni’‘Alisa’ ];   
  2.     
  3. const updatedLists = stringLists.map((strList)=>{   
  4.     <li key={strList.id}> {strList} </li>;   
  5. });   

If there are no stable IDs for rendered items, you can assign the item index as a key to the lists. It can be shown in the below example.

Example

 
  1. const stringLists = [ ‘Peter’‘Sachin’‘Kevin’‘Dhoni’‘Alisa’ ];   
  2.     
  3. const updatedLists = stringLists.map((strList, index)=>{   
  4.     <li key={index}> {strList} </li>;   
  5. });  
  6. Using Keys with component

    Consider you have created a separate component for ListItem and extracting ListItem from that component. In this case, you should have to assign keys on the <ListItem /> elements in the array, not to the <li> elements in the ListItem itself. To avoid mistakes, you have to keep in mind that keys only make sense in the context of the surrounding array. So, anything you are returning from map() function is recommended to be assigned a key.