FrontendDeveloper.in

React question detail

What is "key" prop and what is the benefit of using it in arrays of elements?

A key is a special attribute you should include when mapping over arrays to render data. Key prop helps React identify which items have changed, are added, or are removed.

Keys should be unique among its siblings. Most often we use ID from our data as key:

const todoItems = todos.map((todo) => <li key={todo.id}>{todo.text}</li>);

When you don't have stable IDs for rendered items, you may use the item index as a key as a last resort:

const todoItems = todos.map((todo, index) => (
<li key={index}>{todo.text}</li>
));

Benefits of key:

  • Enables React to efficiently update and re-render components.
  • Prevents unnecessary re-renders by reusing components when possible.
  • Helps maintain internal state of list items correctly.

Note:

  1. Using indexes for keys is not recommended if the order of items may change. This can negatively impact performance and may cause issues with component state.
  2. If you extract list item as separate component then apply keys on list component instead of li tag.
  3. There will be a warning message in the console if the key prop is not present on list items.
  4. The key attribute accepts either string or number and internally convert it as string type.
  5. Don't generate the key on the fly something like key={Math.random()}. Because the keys will never match up between re-renders and DOM created everytime.
Back to all React questions
Get LinkedIn Premium at Rs 399