QA
Senior LevelVue JS

Why does destructuring a Pinia store break reactivity and how does storeToRefs() solve it?

❓ Interview Prompt: Explain Proxy getter interception loss during ES6 destructuring, and storeToRefs() ref wrapping.

Destructuring a Pinia store using ES6 syntax ('const { user, count } = useStore()') extracts the raw primitive values, breaking Vue Proxy getter interception. Subsequent state updates will NOT trigger UI re-renders!

Solution - 'storeToRefs(store)':

'storeToRefs()' wraps every reactive state property and getter in the Pinia store in a 'ref()', preserving reactivity during destructuring while skipping store action functions!

Code Implementation Example

javascript
import { storeToRefs } from 'pinia';
import { useUserStore } from '@/stores/userStore';

const userStore = useUserStore();

// ❌ Destructuring directly breaks reactivity!
// const { user, isAuthenticated } = userStore;

// ✅ storeToRefs wraps properties in refs while preserving reactivity!
const { user, isAuthenticated } = storeToRefs(userStore);
const { login, logout } = userStore; // Actions can be destructured directly!
💡Safely destructuring Pinia store state using storeToRefs.
🎯 Interview Key Takeaway

Use storeToRefs(store) to destructure Pinia store state and getters without breaking Vue Proxy reactivity.

#Pinia#storeToRefs#Reactivity#Senior
Back to all Vue JS Questions→

More Vue JS Interview Questions

Beginner LevelVue JS

What is the difference between Options API and Composition API in Vue 3?

Beginner LevelVue JS

What is the difference between ref() and reactive() in Vue 3?

Beginner LevelVue JS

What is the difference between computed properties, methods, and watch/watchEffect?