Keys: Identity in list updates
🎯 Introduction
Lists are one of the most common page structures. Through two experiments, we will see how keys determine whether Snabbdom moves existing elements or rewrites their content during list updates.
🧱 Experiment 1: update a list without keys
Start by rendering a fruit list:
import { init, h } from 'snabbdom';
const patch = init([]);
// Render a list.
function renderList(list) {
return h(
'ul',
list.map((item) => h('li', item))
);
}
let list = ['Apple', 'Banana', 'Orange'];
let vnode = renderList(list);
vnode = patch(document.getElementById('app'), vnode);
Now insert "Strawberry" at the start of the list:
list = ['Strawberry', 'Apple', 'Banana', 'Orange'];
vnode = patch(vnode, renderList(list));
Inspect the update in developer tools. Snabbdom performs these operations:
| Position | Before | After | Operation |
|---|---|---|---|
| First li | Apple | Strawberry | Rewrite text |
| Second li | Banana | Apple | Rewrite text |
| Third li | Orange | Banana | Rewrite text |
| Fourth li | — | Orange | Create element |
Although we only inserted "Strawberry", the text of all three existing li elements was rewritten. Without keys, Snabbdom reuses elements in place by position: the Nth old and new li have the same selector, so they are treated as the same node and their content is updated.
✨ Experiment 2: add keys
Give each li a key, using the unique fruit name:
function renderList(list) {
// Put key in data.
return h(
'ul',
list.map((item) => h('li', { key: item }, item))
);
}
Insert at the start again. This time, Snabbdom performs these operations:
| Operation | Count |
|---|---|
| Create a "Strawberry" element and insert it at the start | 1 |
| Rewrite the text of "Apple", "Banana", or "Orange" | 0 |
With keys, Snabbdom recognizes that this li still represents the original apple. It preserves the real elements unchanged and creates just one new li. Three text rewrites plus one creation become just one creation.
A key acts as a node's identity. Wherever the node moves within the list, Snabbdom can recognize it and minimize DOM operations.
⚖️ Comparing the two strategies
| Aspect | Without keys | With keys |
|---|---|---|
| Identification | Reuse in place by position | Match by key |
| Insertion at the start | Rewrite text in all following elements | Create only one element |
| Element state, such as input values | Can become associated with the wrong data | Moves with the element and stays associated |
| Suitable use cases | Simple static lists | Dynamic lists with insertions, deletions, or sorting |
Pay particular attention to the third row. If each li contains an input and a user types into the second input, inserting an item at the start leaves the input value at its original position without keys. Because elements are reused by position, the value appears to belong to the wrong item.
🪤 Why array indices make poor keys
If keys only need to be unique, can you use the array index?
// ❌ Not recommended
list.map((item, index) => h('li', { key: index }, item));
After inserting "Strawberry" at the start, every index changes: the original 0(Apple) becomes 1, 1(Banana) becomes 2, and so on. Keys no longer identify the same data items. Snabbdom still rewrites text in place using the new indices, effectively behaving like a list without keys.
Use a unique identifier from the data itself, such as an id returned by the backend:
list.map((item) => h('li', { key: item.id }, item.name));
:key follows the same requirements. Vue 2's list diffing is based on Snabbdom, so the rules you learn here also apply to Vue.❓ Questions and answers
Q1: Are keys rendered into HTML?
No. Keys exist only on virtual node objects for the diffing algorithm to identify nodes. They do not appear in the real DOM.
Q2: Can sibling nodes have duplicate keys?
No. Duplicate keys prevent Snabbdom from distinguishing nodes and make updates unpredictable. Keys must be unique among siblings.
Q3: Are the string '1' and the number 1 the same key?
No. Snabbdom compares keys using strict equality (===), so '1' and 1 are different keys. Keep key types consistent.
Q4: Does a list that only appends items and never reorders need keys?
Omitting keys has little impact when only appending, because old and new elements already align by position. However, use keys whenever insertion, deletion, or sorting is possible.
🧪 Exercise
Render a todo list whose items each have an id and title. Clicking a "Move second item to top" button should move the second item to the start. Render with keys and verify in developer tools that elements only move and their text is not rewritten.
import { init, h } from 'snabbdom';
const patch = init([]);
const todos = [
{ id: 1, title: 'Learn h' },
{ id: 2, title: 'Learn modules' },
{ id: 3, title: 'Learn keys' }
];
// Write your code here.
🎉 You now understand keys! Next, we will explore the complete strategy Snabbdom uses to compare two virtual node trees.
Rendering and updates with patch
Learn the two forms of patch, how initial rendering replaces the container, and the two update paths, and avoid reusing the original container.
How diffing works
Understand Snabbdom's diffing strategy, including same-level comparisons, sameVnode, patchVnode, and double-ended pointers.
