Performance: Sharing composables across components
This affects how efficiently state and logic are reused across Vue components, impacting rendering speed and memory usage.
const sharedCount = ref(0); function useCounter() { function increment() { sharedCount.value++; } return { count: sharedCount, increment }; } // In each component const { count, increment } = useCounter();
function useCounter() { const count = ref(0); function increment() { count.value++; } return { count, increment }; } // In each component const { count, increment } = useCounter();
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Separate reactive state per component | Multiple reactive refs per component | Multiple re-renders on updates | Higher paint cost due to many updates | [X] Bad |
| Shared reactive state via composable | Single reactive ref shared | Single re-render per update | Lower paint cost with fewer updates | [OK] Good |
function useCounter() { const count = ref(0); return { count }; }useTimer inside a Vue component's setup() function?useTimer() to get reactive state, then destructure needed properties.// composable.js
import { ref } from 'vue';
export function useCount() {
const count = ref(0);
function increment() { count.value++; }
return { count, increment };
}
// Component.vue
import { useCount } from './composable';
export default {
setup() {
const { count, increment } = useCount();
increment();
increment();
console.log(count.value);
return {};
}
}increment() is called.import { ref } from 'vue';
export function useData() {
const data = ref(null);
fetch('/api').then(res => res.json()).then(json => data = json);
return { data };
}.value, not be reassigned.data = json instead of data.value = json.Pass the test and this pattern moves unknown