javascript / intermediate
Snippet
Bypassing Deep Reactivity Overhead on Large Datasets with shallowRef
Standard Vue ref wraps arrays and all nested object properties in reactive proxies, which introduces massive memory and CPU overhead when dealing with thousands of items. Using shallowRef together with Object.freeze tracks only top-level reference mutations (.value), drastically reducing garbage collection pressure and optimizing large list handling.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import { shallowRef, triggerRef } from 'vue';export function useLargeDataset() {const records = shallowRef([]);function loadRows(newRows) {records.value = Object.freeze(newRows.map(row => ({...row,processedAt: Date.now()})));}function updateSingleRow(id, updatedFields) {const targetIndex = records.value.findIndex(item => item.id === id);if (targetIndex !== -1) {const updatedArray = [...records.value];updatedArray[targetIndex] = {...updatedArray[targetIndex],...updatedFields};records.value = Object.freeze(updatedArray);triggerRef(records);}}return { records, loadRows, updateSingleRow };}
vue
Breakdown
1
const records = shallowRef([]);
Creates a shallow reactive reference that only reacts to changes at the root level.
2
records.value = Object.freeze(newRows.map(...));
Freezes nested row objects to guarantee immutability and skip deep reactive proxy creation.
3
triggerRef(records);
Explicitly notifies watchers and templates that the shallow reference content has been updated.