Performance: Why state management is needed
State management affects how efficiently a Vue app updates the UI and handles user interactions, impacting rendering speed and responsiveness.
import { createPinia, defineStore } from 'pinia'; const useCounterStore = defineStore('counter', { state: () => ({ count: 0 }), actions: { increment() { this.count++ } } }); // Components use useCounterStore() to access and update state centrally
const sharedData = reactive({ count: 0 }); // Each component imports and modifies sharedData directly without a central store
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Direct shared reactive data without store | Many components update DOM nodes | Multiple reflows triggered | High paint cost due to redundant updates | [X] Bad |
| Centralized state management with Pinia | Only affected components update DOM | Minimal reflows | Lower paint cost with targeted updates | [OK] Good |
State refers to the data that changes over time in your app.ref to create reactive primitive values like numbers.reactive on a primitive, which is incorrect. const count = state(0); uses a non-existent state function. const count = ref(0); correctly uses ref(0). const count = ref({ value: 0 }); creates a ref containing a plain object whose inner properties are not reactive.const state = reactive({ count: 0 });
function increment() {
state.count++;
}
increment();
console.log(state.count);state object is reactive with a count property starting at 0. The increment function increases count by 1.increment() increases state.count from 0 to 1. Then console.log(state.count) outputs 1.const state = reactive({ count: 0 });
function increment() {
state.count += 1;
}
export default { setup() { return { state, increment }; } }increment is called. What is the likely problem?state is reactive and increment correctly updates state.count.state.count in its template, Vue won't know to update the display when it changes.state.count in its template -> Option APass the test and this pattern moves unknown