Imagine buying an apple, a banana, and a pear. Each item has a line number on your receipt. Remove the first item and the remaining line numbers change, even though the products themselves are still the same.

A similar problem can occur in React when we use an array index as a component's key. It seems like a convenient choice. But what happens to a component's local state when the list changes?

Identity is not position

A React key helps React match sibling elements between renders. A key should be unique among its siblings and remain stable for the same logical item.

An apple can occupy index 0 today and index 2 after a list is reversed. Its ID can remain 101 throughout. The array is not the problem: the choice of identity is.

Setting up the experiment

We used an array of objects:

const initialFruits = [ { id: 101, name: "Apple" }, { id: 102, name: "Banana" }, { id: 103, name: "Pear" } ]; 

Each row has an editable comment stored in its own local state. This simplified JSX version illustrates the component (the actual test stand uses React.createElement and Russian labels):

function FruitItem({ name }) { const [value, setValue] = useState(""); return ( <div> <p>{name}</p> <input value={value} onChange={e => setValue(e.target.value)} /> </div> ); } 

Before each test, the rows were reset and filled with three distinct comments: red, yellow and green (translated from the Russian values in the test report).

We tested two actions independently: removing the first fruit and reversing the entire list. Both create a new array without mutating the previous one:

function removeFirst() { setFruits(previous => previous.slice(1)); } function reverseFruits() { setFruits(previous => [...previous].reverse()); } 

The actual test stand uses an equivalent loop for reversal. Only the key strategy varies between the three modes.

Experiment 1: array index as key

{fruits.map((fruit, index) => ( <FruitItem key={index} name={fruit.name} /> ))} 

After removing the apple, the banana occupies position 0. React preserves the state of the component with key 0 and supplies it with the banana's new props. The banana now displays the apple's comment. The pear displays the banana's comment.

Reversing the original list causes a similar mismatch: the pear displays red and the apple displays green. The banana stays in the middle and keeps its yellow comment.

The data moved, but the component identities still corresponded to positions.

Experiment 2: stable IDs

{fruits.map(fruit => ( <FruitItem key={fruit.id} name={fruit.name} /> ))} 

We kept the same array structure and changed the key strategy. After deletion, the banana retained its yellow comment and the pear retained its green comment. Reversal also preserved every fruit's comment.

We did not need to replace the array with a map or hash table. Each logical item simply needed a stable identifier.

A parallel with relational databases

A database can order products differently without breaking the relationships between products and their associated records. A foreign key refers to an eligible unique key rather than to a row's position in a query result.

React keys and SQL constraints are different mechanisms, but the underlying design idea is similar: identity should not depend on position. A React key is not a database constraint and does not enforce referential integrity.

Experiment 3: random keys

{fruits.map(fruit => ( <FruitItem key={Math.random()} name={fruit.name} /> ))} 

Imagine an online shop where the same apple has ID 120 today and ID 140 tomorrow. It becomes difficult to match existing records to the product.

Random keys generated during the parent list's render cause a similar identity problem. When the parent renders again with different keys, React treats those rows as new components. Their local state is initialized again.

In both browser checks, the remaining input values became empty. Random collisions are theoretically possible, but none occurred in these checks.

Generating an ID once when an item is created and storing that ID is different from generating a new key on every render.

Observed results

Key strategy Remove first item Reverse list
Array index Banana: red; pear: yellow Pear: red; banana: yellow; apple: green
Stable ID Banana: yellow; pear: green Pear: green; banana: yellow; apple: red
Random key All remaining inputs empty All inputs empty

All six automated checks matched their predicted values, with no recorded page errors.

Practical recommendations

  • Use stable IDs from your data for dynamic lists.
  • Consider index keys only when the list's membership and order are fixed and items will not be replaced in ways that change their identity.
  • Do not generate keys during rendering. Create and store IDs when data items are created.
  • Remember that stable keys preserve state for matching components of the same type under the same parent. Removing a component still destroys its local state.

A product can move around a catalog and even change its price without changing its identity. The same distinction is worth remembering when building React interfaces.

Method and limitations

The experiment used React 18.2.0, ReactDOM 18.2.0-next-9e3b772b8-20220608, Chromium 144.0.7559.96, and Playwright. The browser test filled actual input elements, clicked the controls and compared the resulting input values and fruit IDs with expected results. The test was performed using locally available libraries rather than the latest React release. These six checks demonstrate the behavior of this specific stand, not a comprehensive test across versions.

The experimental stand, automated tests, technical editing and English translation were prepared with AI assistance. The article's explanations and analogies were developed through a guided learning exercise.

Further reading