---
title: "React keys, identity, and remounting: trace reconciliation with a runnable experiment"
description: "A React key tells React which component instance an element is. Run 9 small scenarios that trace every mount, unmount and DOM change to see when state is kept, moved or lost, and how to fix each case."
author: "Tejas Kumar"
author_url: "https://www.stackandskill.com/authors/tejas-kumar"
published: 2026-11-21
format: deep-dive
tags: ["react"]
tested_with: ["Node.js 22.23.4", "react 19.3.1", "react-dom 19.3.1", "jsdom 25.0.1", "tsx 4.23.15"]
verified: 2026-11-21
reading_time: 10 min
related: ["https://www.stackandskill.com/blog/react-server-components-explained", "https://www.stackandskill.com/blog/catch-broken-json-links-on-localized-pages", "https://www.stackandskill.com/blog/what-happens-when-eight-workers-share-one-odds-api-key"]
url: "https://www.stackandskill.com/blog/react-keys-identity-and-remounting-trace-reconciliation-with-a-runnable"
cite: "Kumar, T. (2026). React keys, identity, and remounting: trace reconciliation with a runnable experiment. Stack & Skill. https://www.stackandskill.com/blog/react-keys-identity-and-remounting-trace-reconciliation-with-a-runnable"
---

# React keys, identity, and remounting: trace reconciliation with a runnable experiment

**A React key tells React which component instance an element is. React keeps an instance (its state, its effects and its [Document Object Model](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model) (DOM) node) when the element's type, its key and its parent all match the last render. When any of them changes React throws the instance away and mounts a new one.** Everything else people say about keys ("they're for lists", "they make rendering faster", "don't use the index") follows from that one sentence.

I wrote a whole book on how React works inside ([Fluent React](https://tej.as/react), which has a chapter on reconciliation) and the fastest way I know to learn this part is to watch React do it. So this post has 9 small scenarios in one file that you can run. Each one prints which instances mounted, which unmounted, which kept their state and what the DOM was asked to do. 3 of them have no list in them at all!

## The experiment: one hook that numbers every instance

You need [Node.js](https://nodejs.org/) and 4 packages. I tested this on Node.js 22.23.4 with `react` and `react-dom` 19.3.1, [`jsdom`](https://github.com/jsdom/jsdom) 25.0.1 (a DOM for Node.js. So no browser is needed) and [`tsx`](https://github.com/privatenumber/tsx) 4.23.15 (it runs the file directly, with no build step).

```sh
mkdir react-keys-trace && cd react-keys-trace
npm init -y
npm install react@19.3.1 react-dom@19.3.1 jsdom@25.0.1 tsx@4.23.15
```

The tracer is one hook. It hands each component instance a number on its first render and logs when that instance mounts and unmounts. If a number survives an update, React kept the instance. A new number means a remount.

```jsx
let log = [];
let nextInstance = 1;

function useTrace(name) {
  const id = useRef(null);
  if (id.current === null) id.current = nextInstance++;
  useEffect(() => {
    log.push(`mount   ${name} #${id.current}`);
    return () => log.push(`unmount ${name} #${id.current}`);
  }, []);
  return id.current;
}
```

The component under test is a row that remembers which item it was born with. That memory is plain `useState`, the same kind of state as a draft in an input, an "expanded" flag or a scroll position.

```jsx
function Row({ item }) {
  const instance = useTrace("Row");
  const [bornAs] = useState(item.name);
  return (
    <li data-instance={instance}>
      {item.name} (state says: {bornAs})
    </li>
  );
}
```

When the row prints `Ada (state says: Ada)` everything is fine. When it prints `Zed (state says: Ada)` you're looking at a bug.

Each scenario renders once, renders again with something changed and counts what happened in between: mounts, unmounts, text rewrites and node inserts, moves or removals. The last 2 come from a [`MutationObserver`](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) on the container so they're what the DOM actually saw. The full file is at the end of this post. Save it as `trace.jsx` and run `npx tsx trace.jsx`.

## Index keys: the state stays put while the data moves

Scenario 1 renders Ada, Brendan and Chidi with `key={index}`, then puts Zed at the top.

```
=== 1. Prepend, key={index} ===

prepend Zed
  mounts: 1, unmounts: 0, text rewrites: 3, node inserts/moves/removals: 1
  #1  Zed (state says: Ada)
  #2  Ada (state says: Brendan)
  #3  Brendan (state says: Chidi)
  #4  Chidi (state says: Chidi)
```

Read that slowly because the problem is all there in 5 lines. Instance #1 used to be Ada's row. Its key was `0` before and it's `0` now so React says "same element, new props" and hands it Zed's data. The state didn't move. Zed is now wearing Ada's state, Ada is wearing Brendan's and the 1 new instance React mounted (#4) went to the _bottom_ of the list for Chidi, who was already there!! React also rewrote 3 text nodes to make the old rows show the new names.

Scenario 2 is the same change with `key={item.id}`, an id that comes from the data:

```
=== 2. Prepend, key={item.id} ===

prepend Zed
  mounts: 1, unmounts: 0, text rewrites: 0, node inserts/moves/removals: 1
  #4  Zed (state says: Zed)
  #1  Ada (state says: Ada)
  #2  Brendan (state says: Brendan)
  #3  Chidi (state says: Chidi)
```

1 mount, 0 text rewrites and every row still owns its own state. React matched the 3 old keys to the 3 old instances and inserted 1 new `<li>` at the top.

Reversing the list (scenarios 3 and 4) shows the same thing from the DOM's side. With index keys React kept all 3 nodes where they were and rewrote the text in 2 of them so `#1` reads `Chidi (state says: Ada)`. With id keys it rewrote nothing and moved the nodes instead:

| Reverse 3 rows | Mounts | Text rewrites | Node moves | State follows the item? |
| --- | --- | --- | --- | --- |
| `key={index}` | 0 | 2 | 0 | No |
| `key={item.id}` | 0 | 0 | 4 | Yes |

`key={index}` is fine when the list never reorders, never gets filtered and never has anything inserted anywhere but the end. Position _is_ identity then and the index says so honestly. The [React docs on list keys](https://react.dev/learn/rendering-lists#keeping-list-items-in-order-with-key) say the same and they're the place to send a teammate who wants the rule without the trace.

## There's a key even when there's no list

Scenario 5 has no array and no `map`. A `Profile` renders 1 `Row`, first for Ada and then for Brendan.

```
=== 5. Same position, no key: switch from Ada to Brendan ===

show Brendan
  mounts: 0, unmounts: 0, text rewrites: 1, node inserts/moves/removals: 0
  #1  Brendan (state says: Ada)
```

0 mounts. Same type, same position, no key so as far as React is concerned this is the same instance getting new props. Brendan's profile now has Ada's state in it. In an app that's the bug where you click from one user to the next and the second user's form still has the first user's half-typed message in it, or their "edit mode" is still on.

The fix is 1 attribute. Scenario 6 is `<Profile key={item.id} item={item} />`:

```
=== 6. Same position, key={item.id}: switch from Ada to Brendan ===

show Brendan
  mounts: 1, unmounts: 1, text rewrites: 0, node inserts/moves/removals: 2
  #2  Brendan (state says: Brendan)
```

Ada's instance unmounted, a new one mounted for Brendan and the state started fresh. A key on a single element is how you tell React "this is a different thing now". It's also the cleanest way to reset a form: change its key and every piece of state under it goes back to its initial value (no effect that watches a prop and calls 5 setters). The React docs call this [resetting state with a key](https://react.dev/learn/preserving-and-resetting-state#option-2-resetting-state-with-a-key).

## A key only counts among siblings

A key isn't global like an `id` in HTML. Scenario 7 renders Ada's row with `key="a"` inside one `<ul>`, then renders it with the same key inside a second `<ul>` next to it.

```
=== 7. Same key, moved to a different parent ===

Ada in the second list
  mounts: 1, unmounts: 1, text rewrites: 0, node inserts/moves/removals: 2
  #2  Ada (state says: Ada)
```

A remount. React only compares an element against the children its parent had last time so the same key under a different parent matches nothing. If you drag a card from one column to another in a board and its state resets, this is why (you'll need to keep that state above both columns).

## A component defined inside a component remounts every time

Scenario 8 has perfectly good keys and still remounts everything:

```jsx
function Outer({ tick }) {
  function InnerRow({ item }) {
    return <Row item={item} />;
  }
  return <ul data-tick={tick}>{people.map((p) => <InnerRow key={p.id} item={p} />)}</ul>;
}
```

```
=== 8. Component defined inside a component, stable keys ===

parent renders again, same data
  mounts: 3, unmounts: 3, text rewrites: 0, node inserts/moves/removals: 6
  #4  Ada (state says: Ada)
  #5  Brendan (state says: Brendan)
  #6  Chidi (state says: Chidi)
```

Same data, same keys and 3 unmounts plus 3 mounts. Every time `Outer` runs it creates a brand new `InnerRow` function. A new function is a new type and a new type means a new instance, however well the key matches. Every input under there loses focus and its text on every parent render. Move the component to the top level of the file and the remounts stop.

## What a random key costs at 1,000 rows

`key={Math.random()}` (or `key={crypto.randomUUID()}` called during render) makes the missing key warning go away. Scenario 9 renders 1,000 rows 10 times with the same data and counts.

```
=== 9. 1,000 rows rendered 10 times with the same data ===
  key={item.id}      : 1000 mounts, 0 unmounts, 377 ms
  key={Math.random()}: 10000 mounts, 9000 unmounts, 605 ms
```

With a stable key React mounts 1,000 rows once and then does nothing 9 times. With a random key no key ever matches. So every render destroys all 1,000 instances and builds 1,000 more: 10× the mounts and 9,000 unmounts for data that never changed. Take the milliseconds with a grain of salt though. That's 1 run in jsdom on a server and your numbers will differ. The mount counts won't. And the time isn't even the worst part because a remount also runs every effect cleanup and setup again, drops focus and restarts any CSS animation.

## How React decides it's the same instance

Put the 9 scenarios together and you get React's test for "is this the same instance?", in the order React checks:

1. **Same parent?** A child is only ever compared with its parent's previous children (scenario 7).
2. **Same key?** Among those siblings React matches by key. With no key, the position is the key (scenarios 1 to 6).
3. **Same type?** If the matched element has a different type (`div` to `span`, `Profile` to `Settings`, or a function recreated on every render), the old instance goes (scenario 8).

3 yeses keep the instance with all its state and update its props. 1 no anywhere is an unmount and a fresh mount. The original write-up of these heuristics is still on the legacy site under [Reconciliation](https://legacy.reactjs.org/docs/reconciliation.html) and it's short.

So when a component's state is somewhere it shouldn't be, or gone when it should be there, drop `useTrace` into it and read the numbers:

- State on the wrong row after a sort, filter or insert? The key is describing position. Use an id that comes from the data and create it when the item is created, never during render.
- State from the last user, tab or record still showing? Same type in the same position. Put `key={thing.id}` on it.
- State resetting when it shouldn't? Look for a key that changes between renders, a parent that changed or a component defined inside another component.
- Want a reset? Change the key on purpose.

## The full file

Copy this into `trace.jsx` next to the `package.json` from the install step and run `npx tsx trace.jsx`. Then change something (try filtering the list, or swapping `<li>` for `<div>` between renders) and guess the counts before you run it again.

```jsx
// Trace what React's reconciler does with keys: which component instances
// mount, which unmount, which keep their state, and what the DOM is asked to do.
// Run: npm install && npm run trace
import { JSDOM } from "jsdom";

const dom = new JSDOM("<!doctype html><div id='root'></div>");
globalThis.window = dom.window;
globalThis.document = dom.window.document;
globalThis.MutationObserver = dom.window.MutationObserver;
globalThis.IS_REACT_ACT_ENVIRONMENT = true;

const React = (await import("react")).default;
const { useEffect, useRef, useState, act } = React;
const { createRoot } = await import("react-dom/client");

// --- the tracer -----------------------------------------------------------
let log = [];
let nextInstance = 1;

// Every component instance gets a number the first time it renders. If the
// number survives an update, React kept the instance. A new number is a remount.
function useTrace(name) {
  const id = useRef(null);
  if (id.current === null) id.current = nextInstance++;
  useEffect(() => {
    log.push(`mount   ${name} #${id.current}`);
    return () => log.push(`unmount ${name} #${id.current}`);
  }, []);
  return id.current;
}

// A row that remembers which item it was born with. That memory is plain
// useState, like a draft in an input or an "expanded" flag.
function Row({ item }) {
  const instance = useTrace("Row");
  const [bornAs] = useState(item.name);
  return (
    <li data-instance={instance}>
      {item.name} (state says: {bornAs})
    </li>
  );
}

async function scenario(title, steps) {
  const container = document.createElement("div");
  document.body.append(container);
  const root = createRoot(container);
  nextInstance = 1;
  console.log(`\n=== ${title} ===`);
  for (const [label, element] of steps) {
    log = [];
    const mutations = [];
    const observer = new MutationObserver((records) => mutations.push(...records));
    observer.observe(container, { childList: true, characterData: true, subtree: true });
    await act(async () => root.render(element));
    mutations.push(...observer.takeRecords());
    observer.disconnect();
    const mounts = log.filter((l) => l.startsWith("mount")).length;
    const unmounts = log.filter((l) => l.startsWith("unmount")).length;
    const text = mutations.filter((m) => m.type === "characterData").length;
    const nodes = mutations.filter((m) => m.type === "childList").length;
    console.log(`\n${label}`);
    console.log(`  mounts: ${mounts}, unmounts: ${unmounts}, text rewrites: ${text}, node inserts/moves/removals: ${nodes}`);
    for (const li of container.querySelectorAll("[data-instance]")) {
      console.log(`  #${li.dataset.instance}  ${li.textContent}`);
    }
  }
  await act(async () => root.unmount());
  container.remove();
}

const people = [
  { id: "a", name: "Ada" },
  { id: "b", name: "Brendan" },
  { id: "c", name: "Chidi" },
];
const withNew = [{ id: "z", name: "Zed" }, ...people];
const reversed = [...people].reverse();

const byIndex = (items) => <ul>{items.map((item, i) => <Row key={i} item={item} />)}</ul>;
const byId = (items) => <ul>{items.map((item) => <Row key={item.id} item={item} />)}</ul>;

// 1 and 2: add an item to the top of a list.
await scenario("1. Prepend, key={index}", [
  ["first render", byIndex(people)],
  ["prepend Zed", byIndex(withNew)],
]);
await scenario("2. Prepend, key={item.id}", [
  ["first render", byId(people)],
  ["prepend Zed", byId(withNew)],
]);

// 3 and 4: reverse the list.
await scenario("3. Reverse, key={index}", [
  ["first render", byIndex(people)],
  ["reverse", byIndex(reversed)],
]);
await scenario("4. Reverse, key={item.id}", [
  ["first render", byId(people)],
  ["reverse", byId(reversed)],
]);

// 5 and 6: no list at all. Same component type in the same position.
function Profile({ item }) {
  return <ul><Row item={item} /></ul>;
}
await scenario("5. Same position, no key: switch from Ada to Brendan", [
  ["show Ada", <Profile item={people[0]} />],
  ["show Brendan", <Profile item={people[1]} />],
]);
await scenario("6. Same position, key={item.id}: switch from Ada to Brendan", [
  ["show Ada", <Profile key={people[0].id} item={people[0]} />],
  ["show Brendan", <Profile key={people[1].id} item={people[1]} />],
]);

// 7: a key only means something among siblings. Same key, new parent.
await scenario("7. Same key, moved to a different parent", [
  ["Ada in the first list", <div><ul><Row key="a" item={people[0]} /></ul><ul></ul></div>],
  ["Ada in the second list", <div><ul></ul><ul><Row key="a" item={people[0]} /></ul></div>],
]);

// 8: a component defined inside another component is a new type every render.
function Outer({ tick }) {
  function InnerRow({ item }) {
    return <Row item={item} />;
  }
  return <ul data-tick={tick}>{people.map((p) => <InnerRow key={p.id} item={p} />)}</ul>;
}
await scenario("8. Component defined inside a component, stable keys", [
  ["first render", <Outer tick={0} />],
  ["parent renders again, same data", <Outer tick={1} />],
]);

// 9: the cost of a key that changes every render, at 1,000 rows over 10 renders.
async function count(title, keyOf) {
  const container = document.createElement("div");
  const root = createRoot(container);
  const many = Array.from({ length: 1000 }, (_, i) => ({ id: `id-${i}`, name: `Person ${i}` }));
  let mounts = 0;
  let unmounts = 0;
  const started = performance.now();
  for (let render = 0; render < 10; render++) {
    log = [];
    await act(async () =>
      root.render(<ul data-render={render}>{many.map((item) => <Row key={keyOf(item)} item={item} />)}</ul>),
    );
    mounts += log.filter((l) => l.startsWith("mount")).length;
    unmounts += log.filter((l) => l.startsWith("unmount")).length;
  }
  const ms = Math.round(performance.now() - started);
  console.log(`  ${title}: ${mounts} mounts, ${unmounts} unmounts, ${ms} ms`);
  await act(async () => root.unmount());
}
console.log("\n=== 9. 1,000 rows rendered 10 times with the same data ===");
await count("key={item.id}      ", (item) => item.id);
await count("key={Math.random()}", () => Math.random());
```

Keys decide which instance you get. Where that instance runs is the next question. [React Server Components: When to Use Server vs. Client Components](https://www.stackandskill.com/blog/react-server-components-explained) here on Stack & Skill covers it.

_Disclosure: I'm the author of Fluent React (O'Reilly). It's linked once above._

_AI assistance: I used Claude to help draft this article and to write and run the experiment. I read every sentence and the output above is from a real run on the versions listed._
