1.

What are keys in React?

Answer»

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(&LT;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.

***Note- Keys used within arrays should be unique among siblings. They need not be globally unique.



Discussion

No Comment Found