Performance: Why composables matter
This affects how efficiently Vue components share and reuse logic, impacting rendering speed and memory usage.
import { ref } from 'vue'; export function useCounter() { const count = ref(0); function increment() { count.value++; } return { count, increment }; } // Components import and call useCounter() to share logic
export default { data() { return { count: 0 }; }, methods: { increment() { this.count++; } } }; // Repeated in many components separately
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Duplicated reactive logic in each component | Multiple reactive watchers per component | Multiple reflows on state change | Higher paint cost due to redundant updates | [X] Bad |
| Shared reactive logic via composables | Single reactive watcher per logic unit reused | Minimal reflows triggered | Lower paint cost with optimized updates | [OK] Good |
function useToggle() {
const on = ref(false);
function toggle() { on.value = !on.value; }
return { on, toggle };
}on.value after calling toggle() twice starting from initial state?on starts as false.false to true. Second toggle flips true back to false.function useData() {
const data = ref(null);
fetch('api/data').then(response => {
data.value = response.json();
});
return { data };
}Pass the test and this pattern moves unknown