Why Index as a Key is a Bad Idea in React
You build a dynamic list in React. You delete an item. Suddenly, the UI state of a different item changes. Or, you sort a list and the input data appears in the wrong components.
This happens because you used the array index as a key.
React uses a system called the Virtual DOM to update your UI. When your state changes, React compares the new tree with the old one. This process is called reconciliation.
The key prop acts like an ID card for your components. It tells React:
- Which item changed.
- Which item is new.
- Which item was removed.
If you use the index as a key, you create problems. Arrays are dynamic. When you add, remove, or reorder items, the index changes.
Here is why this fails:
Performance Issues If you insert an item at the start of a list, every single item after it gets a new index. React thinks every item changed. It re-renders the entire list instead of just the new item.
State Bugs This is the most dangerous part. If your list items have internal state like an input field or a checkbox, the index will cause bugs.
Imagine you type "Important" into the first task's input. You delete that task. If you used the index as a key, React sees that Index 0 still exists. It reuses the old component. Now, your "Important" text appears in the second task's input box.
How to do it right:
- Use Database IDs: Always use the unique ID from your database (like _id or id).
- Generate IDs on the frontend: If you do not have a database, use libraries like uuid or nanoid.
- Use Browser APIs: Use window.crypto.randomUUID() for a built-in way to create unique IDs.
When can you safely use an index? Only if your list meets these three rules:
- The list is static (no adding or deleting).
- The list never reorders (no sorting or filtering).
- The items have no internal state (no inputs or checkboxes).
Stop using index as a key to keep your apps fast and bug-free.
