0
0
Reactframework~5 mins

Keys concept in React

Choose your learning style9 modes available
Introduction

Keys help React keep track of items in a list so it can update the screen efficiently.

When rendering a list of items like a list of tasks or messages.
When you want React to know which item changed, was added, or removed.
When you want to avoid bugs caused by React mixing up list items.
When you want smoother and faster updates in your app's user interface.
Syntax
React
<ul>
  {items.map(item => (
    <li key={item.id}>{item.name}</li>
  ))}
</ul>

The key must be a unique and stable value for each item.

Do not use array index as key if the list can change order or items.

Examples
Using a unique id from each fruit as the key.
React
const fruits = [{id: 'a', name: 'Apple'}, {id: 'b', name: 'Banana'}];

return (
  <ul>
    {fruits.map(fruit => (
      <li key={fruit.id}>{fruit.name}</li>
    ))}
  </ul>
);
Using index as key is okay only if the list never changes order or items.
React
const numbers = [10, 20, 30];

return (
  <ul>
    {numbers.map((num, index) => (
      <li key={index}>{num}</li>
    ))}
  </ul>
);
Keys can be used on any element inside a list, not just <li>.
React
const tasks = [{id: 1, title: 'Clean'}, {id: 2, title: 'Cook'}];

return (
  <div>
    {tasks.map(task => (
      <p key={task.id}>{task.title}</p>
    ))}
  </div>
);
Sample Program

This component shows a list of todo items. Each item has a unique id used as the key. This helps React update the list efficiently if items change.

React
import React, { useState } from 'react';

export default function TodoList() {
  const [todos, setTodos] = useState([
    { id: 't1', text: 'Learn React' },
    { id: 't2', text: 'Build App' },
    { id: 't3', text: 'Deploy' }
  ]);

  return (
    <section>
      <h2>My Todo List</h2>
      <ul>
        {todos.map(todo => (
          <li key={todo.id}>{todo.text}</li>
        ))}
      </ul>
    </section>
  );
}
OutputSuccess
Important Notes

Always use a unique and stable key to avoid unexpected UI bugs.

Keys help React identify which items changed, so it can update only those parts.

Using array index as key can cause problems if the list changes order or items.

Summary

Keys are unique IDs for list items in React.

They help React update lists efficiently and correctly.

Always use stable and unique keys, not array indexes if the list can change.