React - Lists & Keys

Lists & Keys

When rendering arrays, provide a stable key for each item.

Try it: Todo List (Static)

View source
function TodoList(){
  const todos = [
    { id: 1, text: 'Learn JSX' },
    { id: 2, text: 'Understand props/state' },
    { id: 3, text: 'Build components' },
  ];
  return (
    <ul>
      {todos.map(item => <li key={item.id}>{item.text}</li>)}
    </ul>
  );
}
ReactDOM.createRoot(document.getElementById('try-lists')).render(<TodoList />);

Syntax primer (for newcomers)

  • array.map(item => ...) to render lists.
  • key helps React match elements to data items; use stable IDs (not indexes) when possible.

Common pitfalls

  • Using array index as key can cause odd UI behavior during reordering.
  • Ensure keys are unique among siblings.

Vocabulary

  • Key: Identifier that helps React keep items matched to their DOM nodes.
  • Reconciliation: Diffing process React uses to update lists efficiently.

Checks for Understanding

  1. Why are stable keys important when rendering lists?
  2. When is it acceptable to use the array index as a key?
Show answers
  1. They help React match items between renders to avoid incorrect DOM updates.
  2. When the list is static and never reordered/filtered/inserted (e.g., a fixed menu).

Exercises

  1. Convert the static array to an editable list with an “Add” button. Ensure newly added items get unique, stable keys.
  2. Demonstrate a reorder (move item up/down) and verify that item state stays with the right row by using stable keys.
  3. Render a list of objects fetched from a mock API (array of {id, name}); use id as the key.