← React Beginner Questions - Set 2 Q18

What is the role of keys in React lists?

React Beginner Questions - Set 2

Keys are how React recognises an item across renders. Using the array index looks fine until items are reordered or removed.

Example

import { useState } from 'react';

export default function TodoList() {
  const [todos, setTodos] = useState([
    { id: 'a1', text: 'Write tests' },
    { id: 'a2', text: 'Deploy' },
  ]);

  function removeFirst() {
    setTodos(prev => prev.slice(1));
  }

  return (
    <>
      <ul>
        {todos.map(todo => (
          <li key={todo.id}>{todo.text}</li>   // stable, unique, not the index
        ))}
      </ul>
      <button onClick={removeFirst}>Remove first</button>
    </>
  );
}

What to notice

← Back to the question list