Vue JS Vue JS State Management 1 — Questions and Answers
Question 1: What is the primary purpose of Pinia in a Vue 3 application?
- Template rendering engine
- Centralized state management store (Correct answer)
- HTTP client library
- CSS-in-JS solution
Correct answer: Centralized state management store
Pinia is the official Vue 3 state management library that provides centralized, reactive stores with a simpler API than Vuex.
Question 2: In Pinia, what is the difference between state, getters, and actions?
- They are all identical and interchangeable
- state holds data, getters are computed values, actions contain logic/mutations (Correct answer)
- getters replace components, actions replace watchers
- state is async, getters are sync, actions are static
Correct answer: state holds data, getters are computed values, actions contain logic/mutations
state is the reactive data, getters are cached computed properties derived from state, and actions are methods that can be synchronous or asynchronous.
Question 3: How do you define a Pinia store using the Options API style?
- const store = new Pinia({ id: 'myStore', state: () => ({}) })
- const useMyStore = defineStore('myStore', { state: () => ({}), getters: {}, actions: {} }) (Correct answer)
- export default createStore({ state: {} })
- const store = usePinia().createStore({ name: 'myStore' })
Correct answer: const useMyStore = defineStore('myStore', { state: () => ({}), getters: {}, actions: {} })
defineStore() accepts a unique store id and an options object with state, getters, and actions, returning a composable use function.
Question 4: How do you access a Pinia store inside a Vue 3 component?
- import store from '@/stores/myStore'
- const store = useMyStore() inside setup() (Correct answer)
- Inject it via the Vue plugin system manually
- Access it via this.$pinia.myStore
Correct answer: const store = useMyStore() inside setup()
You call the composable returned by defineStore() inside a component's setup() function to get the reactive store instance.
Question 5: Which Pinia method allows you to patch multiple state properties at once?
- store.commit()
- store.$patch() (Correct answer)
- store.setState()
- store.$merge()
Correct answer: store.$patch()
$patch() accepts an object of partial state updates or a mutation function, updating multiple properties efficiently in one operation.
Question 6: In Vuex 4, what is a mutation and why must state changes go through it?
- An async API call handler
- A synchronous function that is the only valid way to change Vuex state, enabling devtools tracking (Correct answer)
- A computed property for the store
- A plugin hook for middleware
Correct answer: A synchronous function that is the only valid way to change Vuex state, enabling devtools tracking
Mutations are synchronous functions that directly modify state, and Vuex enforces this pattern so every change is trackable in Vue Devtools.
What is the primary purpose of Pinia in a Vue 3 application?