Performance: Custom refs with customRef
This affects how reactive state updates trigger DOM updates and component re-renders in Vue applications.
import { customRef } from 'vue'; function useDebouncedRef(value, delay = 200) { let timeout; return customRef((track, trigger) => ({ get() { track(); return value; }, set(newValue) { clearTimeout(timeout); timeout = setTimeout(() => { value = newValue; trigger(); }, delay); } })); } const count = useDebouncedRef(0);
import { ref } from 'vue'; const count = ref(0); function increment() { count.value++; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Standard ref with immediate updates | Many reactive triggers | 1 reflow per update | High paint cost on frequent changes | [X] Bad |
| customRef with debounced updates | Fewer reactive triggers | Single reflow per batch | Lower paint cost due to fewer updates | [OK] Good |
customRef in Vue?customRef doescustomRef allows you to create reactive references where you control how the value is read and written.customRef.customRef in a Vue 3 component?customRef as a named export, so it must be imported with curly braces.myRef.value = 10 is called?import { customRef } from 'vue';
const myRef = customRef((track, trigger) => {
let value = 0;
return {
get() {
track();
return value;
},
set(newValue) {
if (newValue !== value) {
value = newValue;
trigger();
console.log('Value updated');
}
}
};
});
myRef.value = 10;import { customRef } from 'vue';
const myRef = customRef((track, trigger) => {
let value = 0;
return {
get() {
return value;
},
set(newValue) {
value = newValue;
trigger();
}
};
});track() to register dependencies. Here, it returns value without calling track(), so reactivity won't work properly.customRef that debounces updates by 300ms before triggering reactivity. Which code snippet correctly implements this behavior?Pass the test and this pattern moves unknown