0
0
Vueframework~8 mins

Defining state in stores in Vue - Performance & Optimization

Choose your learning style9 modes available
Performance: Defining state in stores
MEDIUM IMPACT
This affects page load speed and interaction responsiveness by controlling how state changes trigger component updates and re-renders.
Managing application state in a Vue store
Vue
import { ref } from 'vue';

export function useStore() {
  const user = ref(null);
  const items = ref([]);

  function updateUser(newUser) {
    user.value = newUser;
  }

  function addItem(item) {
    items.value.push(item);
  }

  return { user, items, updateUser, addItem };
}
Splitting state into smaller refs allows Vue to track dependencies precisely, so only components using changed state re-render.
📈 Performance Gainreduces re-renders to only affected components, improving interaction responsiveness
Managing application state in a Vue store
Vue
import { reactive } from 'vue';

export const store = reactive({
  user: null,
  items: [],
  updateUser(newUser) {
    this.user = newUser;
  },
  addItem(item) {
    this.items.push(item);
  }
});
Using a large reactive object for the entire store causes all components using any part of the store to re-render on any state change, even if unrelated.
📉 Performance Costtriggers many unnecessary re-renders and reactive tracking overhead
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Large reactive store objectHigh (many components re-render)High (many reflows triggered)High (many paints)[X] Bad
Small reactive refs per state pieceLow (only affected components re-render)Low (minimal reflows)Low (minimal paints)[OK] Good
Rendering Pipeline
When state in the store changes, Vue's reactivity system tracks dependencies and triggers component updates. Efficient state definition minimizes the number of components that need to update.
Dependency Tracking
Component Update
Render
⚠️ BottleneckComponent Update stage due to unnecessary re-renders
Core Web Vital Affected
INP
This affects page load speed and interaction responsiveness by controlling how state changes trigger component updates and re-renders.
Optimization Tips
1Split store state into small reactive refs or computed properties.
2Avoid using one large reactive object for all state.
3Only update state pieces that actually change to minimize re-renders.
Performance Quiz - 3 Questions
Test your performance knowledge
What is a performance benefit of defining state as small reactive refs in a Vue store?
AState updates block rendering longer
BOnly components using changed state re-render
CAll components re-render faster
DIt increases bundle size significantly
DevTools: Performance
How to check: Record a performance profile while interacting with the app. Look for excessive component updates and long scripting times.
What to look for: Check if many components update on unrelated state changes, indicating inefficient state definition.