The Principle of the Key Attribute in Virtual DOM
In the diff algorithm of the Virtual DOM, the key attribute is used to identify the uniqueness of nodes, helping the framework efficiently match old and new nodes during the update process. The following analysis explains its principle and function step by step.
1. Why is a Key Needed?
Scenario Example:
Assume the old node list is [A, B, C], and the new node list is [A, C, B].
Without a key, the diff algorithm compares sequentially:
- Old A vs New A → Reuse
- Old B vs New C → Different type, delete B and create C
- Old C vs New B → Different type, delete C and create B
Result: Triggers 2 deletions and 2 creations, which is inefficient.
2. How the Key Works
After adding a key (e.g., using data ID as the key):
- The algorithm establishes a mapping between keys and nodes (e.g.,
{1:A, 2:B, 3:C}). By comparing the order changes of keys between the old and new lists:- Detects that the key order in the new list is
[1, 3, 2](corresponding to A, C, B). - Uses double-ended comparison or longest increasing subsequence (optimization strategies in Vue3/React) to find the minimum movement path: only needs to move B after C.
Result: Requires only 1 node movement, avoiding repeated rendering.
- Detects that the key order in the new list is
3. Principles for Binding Keys
- Must be stable: Keys should be based on unique data identifiers (e.g., ID), not random numbers or indices.
- Avoid using indices as keys:
If array indices are used as keys, inserting an element in the middle of the list causes the keys of all subsequent elements to change, leading to many nodes being incorrectly judged as needing updates.
4. Specific Implementation in Frameworks
React:
- In the
reconcileChildrenphase, it determines whether nodes are the same based on keys. - If keys are the same but types differ, the old node is still destroyed and a new one is created.
Vue3:
- In
patchChildren, dynamic child nodes (v-for) are quickly matched based on keys. - Uses a
Mapto store key indices and calculates the minimum number of moves viagetSequence.
5. Usage of Keys in Special Scenarios
- Forcing component reset: Changing a component's key triggers its destruction and reconstruction, often used to reset component state (e.g., switching users in a form).
- Dynamic components: In Vue's
\u003ccomponent :is="..."\u003e, keys ensure lifecycle hooks are correctly triggered during component switching.
6. Summary
The core principle of the key is to provide an identity for virtual nodes, enabling the diff algorithm to precisely track node changes, reduce unnecessary DOM operations, and improve performance. Incorrect use of keys can lead to rendering errors or performance degradation.