javascript / expert
Snippet
Optimizing Large Lists with ShallowRef
When dealing with thousands of objects, standard ref recursion can cause significant overhead. shallowRef only tracks the .value property itself. It skips deep reactivity conversion for nested objects, providing a massive performance boost for immutable data structures or external library instances.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
import { shallowRef } from 'vue';const heavyList = shallowRef([{ id: 1, data: new Array(1000).fill(0) },{ id: 2, data: new Array(1000).fill(0) }]);// Trigger update by replacing the whole valuefunction updateList() {const newList = [...heavyList.value];newList.push({ id: 3, data: [] });heavyList.value = newList;}
vue
Breakdown
1
const heavyList = shallowRef([...]);
Creates a ref that is only reactive at the root level, not recursively.
2
heavyList.value = newList;
Updates are only detected when the entire reference is replaced.
3
newList = [...heavyList.value];
Requires an immutable approach to trigger the reactive system since internal mutations are ignored.