Performance: Using stores in components
Using stores in Vue components affects how state updates trigger component re-renders and how efficiently data flows through the app.
import { useStore } from 'vuex'; import { computed } from 'vue'; export default { setup() { const store = useStore(); const count = computed(() => store.getters['getCount']); return { count }; } }
import { useStore } from 'vuex'; import { computed } from 'vue'; export default { setup() { const store = useStore(); const count = computed(() => store.state.count); return { count }; } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Direct store state access in many components | High (many reactive dependencies) | High (many re-renders) | High (many paints) | [X] Bad |
| Using selective getters and mutations | Low (minimal reactive dependencies) | Low (targeted re-renders) | Low (fewer paints) | [OK] Good |
setup() function?useStore().const store = useStore() correctly calls the store function inside setup().import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
actions: {
increment() { this.count++ }
}
})const counter = useCounterStore() counter.increment() console.log(counter.count)
count = 0. Calling increment() increases count by 1.counter.increment(), counter.count becomes 1, so logging it prints 1.import { useCounterStore } from '@/stores/counter'
export default {
setup() {
const counter = useCounterStore
counter.increment()
return { counter }
}
}counter = useCounterStore without parentheses, so it stores the function itself, not the store instance.counter.increment() fails because counter is a function, not the store object.setup() to achieve this?const taskStore = useTaskStore()
function addTask(task) {
if (task && !taskStore.tasks.includes(task)) {
taskStore.tasks.push(task)
}
correctly calls useTaskStore() to get the store instance and defines addTask with proper checks.task is not empty and not already in taskStore.tasks before pushing, preventing duplicates and empty entries.Pass the test and this pattern moves unknown