What is the significance of keys in ReactJS and what is its purpose?

What is the significance of keys in ReactJS and what is its purpose?
----------------------------------------------

In react application when its comes to rendering a list of items as that moment if we ignore the key attribute, it will not cause any rendering issue.

But if we do not provide a key attribute during rendering, we get a warning in our react application. To remove that warning and optimise our code, we provide a key.

So the main role of "key" attribute is to identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity.

The best and most efficient way to pick a key is to take an ID from your data, which you are getting as an API or any data.

 Lets take an example 

In this example we have used user's id because as key whenever there is a change in items of the list. Using id’s are in the key attribute is the best way to provide keys and make better performance.

  1. import React from 'react';  
  2.   
  3. import Card from '../UI/Card';  
  4. import classes from './UsersList.module.css';  
  5.   
  6. const UsersList = (props) => {  
  7.   return (  
  8.     <Card className={classes.users}>  
  9.       <ul>  
  10.         {props.users.map((user) => (  
  11.           <li key={user.id}>  
  12.             {user.name} ({user.age} years old)  
  13.           </li>  
  14.         ))}  
  15.       </ul>  
  16.     </Card>  
  17.   );  
  18. };  
  19.   
  20. export default UsersList;  

Categories: ReactJs Tags: #ReactJs,

Newsletter Subcribe

Receive updates and latest news direct from our team. Simply enter your email.