Rendering and data flow

Give list items stable keys

Help React match each rendered item with the same data item across insertions, removals, and reordering.

A key identifies an item among its siblings across renders.

{tasks.map(task => (
  <Task key={task.id} task={task} />
))}

When tasks move, React uses each ID to keep component and DOM state with the correct task.

Array indexes are unsafe when items can be inserted, removed, sorted, or filtered. If the first task is removed, the item now at index zero can inherit the previous first component’s input state.

Generate IDs when data is created, not while rendering. key={Math.random()} changes identity on every render and forces React to recreate the subtree.

Keys need to be unique only among siblings. The same task ID can appear in a separate list.

key is for React and is not passed as a normal prop. Pass id={task.id} separately when the component needs it.

Build a list with editable inputs, then sort it. Compare stable IDs with index keys and watch which text stays with each item.

Lesson completed

Take this course offline

Get every free book, course edition, and software download.

Get the download library →