← React Beginner Questions - Set 2 Q18
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.
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>
</>
);
}