--- title: Use storeToRefs When Destructuring Pinia Stores impact: HIGH impactDescription: Destructuring Pinia stores directly breaks reactivity - state changes won't trigger UI updates type: gotcha tags: [vue3, pinia, state-management, reactivity, destructuring] --- # Use storeToRefs When Destructuring Pinia Stores **Impact: HIGH** - Pinia stores are wrapped with `reactive`, so destructuring them directly extracts non-reactive values. Changes to the store won't be reflected in your component, causing stale UI and confusing bugs. This is one of the most common mistakes when using Pinia, especially for developers coming from Vuex or other state management libraries. ## Task Checklist - [ ] Never destructure state or getters directly from a Pinia store - [ ] Use `storeToRefs()` to extract reactive state and getters - [ ] Destructure actions directly (they don't need reactivity) - [ ] Remember: `storeToRefs` is for state/getters, direct destructure is for actions ## The Problem: Direct Destructuring ```vue ``` ## The Solution: Use storeToRefs ```vue ``` ## Understanding Why This Happens Pinia stores are reactive objects (like `reactive()`). When you destructure: ```javascript const store = useCounterStore() // store is a reactive Proxy const { count } = store // count is now just a primitive number (0), not reactive // It's like doing: const count = 0 // vs with storeToRefs const { count } = storeToRefs(store) // count is now a ref that stays connected to the store // It's like: const count = computed(() => store.count) ``` ## Complete Pattern: State, Getters, and Actions ```vue ``` ## Alternative: Don't Destructure If you prefer, you can avoid destructuring entirely: ```vue ``` This works fine but is more verbose for stores used frequently in the template. ## Common Mistake: Mixing storeToRefs with Actions ```vue ``` ## TypeScript Tip With TypeScript, the types work correctly: ```typescript import { storeToRefs } from 'pinia' import { useUserStore } from '@/stores/user' const userStore = useUserStore() // name is Ref, email is Ref const { name, email } = storeToRefs(userStore) // login is (credentials: Credentials) => Promise const { login } = userStore ``` ## Reference - [Pinia - Destructuring from a Store](https://pinia.vuejs.org/core-concepts/#destructuring-from-a-store) - [Pinia API - storeToRefs](https://pinia.vuejs.org/api/modules/pinia.html#storetorefs)