0 votes
in ReactJS by
What are keys in React?

1 Answer

0 votes
by

A key is a special string attribute that needs to be included when using lists of elements.

Example of a list using key:

const ids = [1,2,3,4,5];

const listElements = ids.map((id)=>{

 return(

 <li key={id.toString()}>

   {id}

 </li>

 )

})

Importance of keys

Keys help react identify which elements were added, changed or removed.

Keys should be given to array elements for providing a unique identity for each element.

Without keys, React does not understand the order or uniqueness of each element.

With keys, React has an idea of which particular element was deleted,edited, and added.

Keys are generally used for displaying a list of data coming from an API.

Related questions

0 votes
asked Jul 2, 2019 in ReactJS by Venkatshastri
0 votes
asked Nov 8, 2023 in ReactJS by GeorgeBell
...