Performance: Typing ref and reactive
Typing refs and reactive objects affects how Vue tracks changes and updates the DOM, impacting rendering speed and responsiveness.
import { ref } from 'vue'; const count = ref<number>(0);
import { ref } from 'vue'; const count = ref(null); count.value = 0;
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Untyped ref | Reactive tracking on all changes | Multiple reflows on updates | Higher paint cost due to redundant updates | [X] Bad |
| Typed ref | Optimized reactive tracking | Single reflow per update | Lower paint cost with batched updates | [OK] Good |
| Untyped reactive object | Deep reactive tracking triggers many updates | Multiple reflows on nested changes | High paint cost due to layout thrashing | [X] Bad |
| Typed reactive object | Selective reactive tracking | Minimal reflows on relevant changes | Reduced paint cost with efficient updates | [OK] Good |
ref for simple valuesref<Type> is used to create reactive primitive values like numbers or strings with type safety.ref<number>(0) correctly creates a reactive number initialized to 0.ref<number>(0) -> Option Areactive<Type> to create reactive objects with type safety.const state = reactive<{ count: number }>({ count: 0 }) correctly types the object and makes it reactive.const state = reactive<{ count: number }>({ count: 0 }) -> Option Bconst count = ref<number>(5); count.value = 10; console.log(count.value);
ref<number>(5) creates a reactive number with initial value 5. To update or read the value, use .value.count.value = 10 updates the reactive value. Logging count.value outputs 10.const state = reactive<{ count: number }>({ count: 0 });
state.count = 'one';{ count: number }, so count must be a number.'one' (a string) to count violates the type, causing a type error.id: number and name: string. Which is the best way to type and initialize this state?ref for arrays to keep reactivity simple and clear.Array<{ id: number; name: string }> ensures each user object has correct properties.ref<Array<{ id: number; name: string }>>([]) initializes an empty reactive array with proper typing.const users = ref<Array<{ id: number; name: string }>>([]) -> Option APass the test and this pattern moves unknown