日本語

Why React Input Values Shift to the Wrong Row When key Is an Index

​​React​Forms,Playwright,TypeScript,useState

When you build a list of inputs in React and pass the array index as key, deleting a row in the middle makes the deleted row's input value appear in the next row. Passing a stable ID for each row as key prevents the shift. This bug happens in forms where rows can be deleted, such as an order form where you can add and remove line items, or a to-do list where each item has a memo.

I reproduced this shift in a test environment. Before and after a deletion, I checked each row's label, the value in its input, and which input element stayed on screen. I compared three cases: the input value held by the input element itself, held in the row component's state, and held in the list's array state. For each case, I used the index as key and then the ID.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.4, react and react-dom 19.3.1, and TypeScript 7.0.2. I bundled the code for development with esbuild, opened it in Chromium 153 driven by Playwright 1.63.0, and performed input and delete button clicks. The components were wrapped in StrictMode. I did not test Vite or other build tools, Next.js, or browsers other than Chromium.

Deleting a row in the middle shifts the memo to the row below

The following list has three rows: apple, orange, and grape. Each row has a memo input and a delete button. The labels in the test data are in Japanese, so the code below uses them as-is, and I refer to the rows by their English meanings. The inputs have no value prop, so the typed text lives in the input element itself. The key is the index from the second argument of map.

ts
export type Item = { id: string; name: string };

export const initialItems: Item[] = [
  { id: 'apple', name: 'りんご' },
  { id: 'orange', name: 'みかん' },
  { id: 'grape', name: 'ぶどう' },
];
tsx
import { useState } from 'react';
import { initialItems, type Item } from './items';

export default function MemoList() {
  const [items, setItems] = useState<Item[]>(initialItems);

  function remove(id: string) {
    setItems(items.filter((item) => item.id !== id));
  }

  return (
    <ul>
      {items.map((item, index) => (
        // Wrong: key is set to the array position
        <li key={index}>
          <label>
            {item.name}のメモ <input />
          </label>
          <button type="button" onClick={() => remove(item.id)}>
            {item.name}を削除
          </button>
        </li>
      ))}
    </ul>
  );
}

In the test, I made the key switchable between index and id through a prop.

I typed the memos Fuji, Unshu, and Kyoho into the three inputs and then clicked the delete button for the orange row. The following shows each row before and after the deletion.

text
--- List with index passed as key
削除前: りんごのメモ=「ふじ」(入力欄 #1) / みかんのメモ=「温州」(入力欄 #2) / ぶどうのメモ=「巨峰」(入力欄 #3)
削除後: りんごのメモ=「ふじ」(入力欄 #1) / ぶどうのメモ=「温州」(入力欄 #2)
--- List with id passed as key
削除前: りんごのメモ=「ふじ」(入力欄 #1) / みかんのメモ=「温州」(入力欄 #2) / ぶどうのメモ=「巨峰」(入力欄 #3)
削除後: りんごのメモ=「ふじ」(入力欄 #1) / ぶどうのメモ=「巨峰」(入力欄 #3)

The #1-style numbers are marks I wrote into each input element (data-mark attribute) from top to bottom before the deletion. After the deletion, they show which element is still on screen. In the output, I replaced the list names that the test script had assigned with easier-to-understand wording.

In the list using index as key, the orange row disappeared, and the grape row's memo became "Unshu". The "Kyoho" that I typed in the grape row was gone from the screen. In the list using id as key, the grape row still showed "Kyoho".

Two lists with the same memos entered. In the top list, the one with index passed as key (its title is in Japanese in the image), clicking the delete button for the orange row makes the grape input turn pink and show "Unshu". In the bottom list, the one with id passed as key (its title is in Japanese in the image), clicking the same button leaves the grape input at "Kyoho". The labels in the image are in Japanese.
The delete button for the orange row clicked once in each list. The button just clicked and the grape input right after the click are highlighted in pink.

The GIF is a demo that places two lists built the same way as the list above, one above the other, with headings and a status bar added. Just after the click, it highlights the button and the grape input and status bar in pink for a moment.

What is shifting when the index is the key

The marks show what happened. In the list using index as key, the inputs that remained were #1 and #2, and the one removed was #3 at the bottom. Element #2, which had belonged to the orange row, was reused as the grape row.

After the deletion, the array is [apple, grape], so the keys are 0 and 1. React sees that the rows with keys 0 and 1 still exist and that the row with key 2 is gone. It then updates the label and button text of the row with key 1 to "grape" and reuses the input element without recreating it. As a result, "Unshu", which was still in that input element, appears next to the grape label.

In the list using id as key, the inputs that remained were #1 and #3, and the one removed was #2 from the orange row. This is because React sees that the row with key orange was removed.

The official Rendering Lists page warns that using the index as key causes confusing bugs when items are added, removed, or reordered. It also explains that React uses the index when no key is given.

Warning

With the index as key, no key warning appears in the console. In my test, the only console output was a message suggesting React DevTools. Because the console shows no warning, you cannot notice the shift from it.

Deleting the first row shifts every row

I reloaded the page, entered the memos again, and then clicked the delete button for the first row, the apple row.

text
--- List with index passed as key
削除後: みかんのメモ=「ふじ」(入力欄 #1) / ぶどうのメモ=「温州」(入力欄 #2)
--- List with id passed as key
削除後: みかんのメモ=「温州」(入力欄 #2) / ぶどうのメモ=「巨峰」(入力欄 #3)

In the index list, both remaining rows showed the memo from the row above them. The orange row showed "Fuji", and the grape row showed "Unshu". Every row below the deleted position shifted. In the ID list, the orange and grape memos stayed the same.

Shifting also happens when the memo is in the row component's state

I passed a value to the input and stored the memo in the row component's state. The result was the same.

tsx
function Row({ item, onRemove }: { item: Item; onRemove: (id: string) => void }) {
  const [memo, setMemo] = useState('');
  return (
    <li>
      <label>
        {item.name}のメモ <input value={memo} onChange={(e) => setMemo(e.target.value)} />
      </label>
      <button type="button" onClick={() => onRemove(item.id)}>
        {item.name}を削除
      </button>
    </li>
  );
}

When the parent wrote <Row key={index} ... /> and I deleted the orange row, the grape row's memo became "Unshu". With <Row key={item.id} ... />, it stayed "Kyoho".

As the state preservation and reset page explains, React ties state to a position in the tree, not to the component itself. With index as key, the Row at key 1 is treated as the same component before and after the deletion, so its state "Unshu" carries over to the grape row. The same page's challenge on fixing misplaced state in a list also identifies the cause as using the index as key.

Storing the value in the array does not shift the display

I also tried storing each memo in the list's array state, one per item, and passing value={row.memo} to the input.

tsx
type Row = { id: string; name: string; memo: string };

const [rows, setRows] = useState<Row[]>(initialItems.map((item) => ({ ...item, memo: '' })));

function changeMemo(id: string, memo: string) {
  setRows(rows.map((row) => (row.id === id ? { ...row, memo } : row)));
}

The result after deleting the orange row was as follows.

text
--- List holding notes in an array, with index passed as key
削除後: りんごのメモ=「ふじ」(入力欄 #1) / ぶどうのメモ=「巨峰」(入力欄 #2)
--- List holding notes in an array, with id passed as key
削除後: りんごのメモ=「ふじ」(入力欄 #1) / ぶどうのメモ=「巨峰」(入力欄 #3)

With this pattern, even with index as key, the grape memo still showed "Kyoho" after the orange row was deleted. Because the memo is removed along with the item's data, the display does not shift.

However, the marks show that the input left in the grape row was #2, the element that had been used for the orange row. With index as key, React still reuses elements by position even in this pattern. The value is written from the data on every render, so the screen looks correct, but in terms of how key works, it is the same as the pattern that shifts.

Point

In a list where rows can be added or removed, pass a stable ID that does not change for each item as key, wherever the value is held.

For where to get IDs, the official Rendering Lists page explains that data from a database should use its existing ID, and data created in the browser should get an ID when it is created, such as a counter or crypto.randomUUID().

Using the index as key is only safe for a list where rows are never added, removed, or reordered, like the poem-line example in the official Rendering Lists page.

​Posted by 86