Importance of keys in React.js

Keys helps to identify which item have changed or added or removed. Keys are assigned to the elements in an array to identify them.

Example:

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

const listItems = numbers.map((number) =>

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

    {number}

  </li>

);

React will ensure that any child with the key will be reordered or destroyed. In React to understanding the element, identity is important for performance and minimizing DOM manipulation. Keys should be always unique and constant. Never use index and Math.random() as a key value. In the virtual DOM, everything doesn’t have direct representation therefore, any direct manipulation on the DOM will be unnoticed by React reconciler and without a unique key.