Performance: Reactive Map and Set
This affects how Vue tracks changes in Map and Set collections, impacting update speed and rendering responsiveness.
const myMap = ref(new Map()); // Batch updates by replacing the Map const tempMap = new Map(); for (let i = 0; i < 100; i++) { tempMap.set(i, i * 2); } myMap.value = tempMap;
const myMap = reactive(new Map()); // Updating inside a loop for (let i = 0; i < 100; i++) { myMap.set(i, i * 2); }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Multiple individual Map.set() calls | Many reactive triggers | 1 reflow (batched) | Medium paint cost | [X] Bad |
| Batch Map replacement | Single reactive trigger | Single reflow | Low paint cost with one update | [OK] Good |
| Multiple individual Set.add() calls | Many reactive triggers | 1 reflow (batched) | Medium paint cost | [X] Bad |
| Batch Set replacement | Single reactive trigger | Single reflow | Low paint cost | [OK] Good |
Map reactive so that UI updates when it changes?reactive() wraps objects like Map or Set to track changes.reactive() can wrap Map to make it reactive, so UI updates on mutations.reactive(new Set()) is correct; Set() without new is invalid, and ref() wraps primitives.const myMap = reactive(new Map());
myMap.set('a', 1);
myMap.set('b', 2);
myMap.delete('a');
console.log([...myMap.keys()]);
What will be logged to the console?const myMap = reactive(Map());
myMap.set('key', 'value');new Map(), not just Map().const mySet = reactive(new Set(['apple', 'banana']));
// Later in code
mySet.add('banana');
mySet.delete('apple');
const items = [...mySet];
What will be the value of items after these operations?Pass the test and this pattern moves unknown