Middle
Where can the state be stored in Vue? When is it better to use Pinia/Vuex, and when provide/inject?
sobes.tech AI
Answer from AI
In Vue, state can be stored in several ways:
- Local component state — data inside the
data()of a specific component. - Provide/Inject — a mechanism for passing data from parent to descendants without props, suitable for limited hierarchical data sharing.
- Global state via Pinia or Vuex — a centralized store for the entire application.
When to use:
-
Provide/Inject
- When you need to pass data or functions deep down the component tree without passing props.
- For small, local dependencies.
- Not suitable for reactive global state, as tracking changes is difficult.
-
Pinia/Vuex
- For managing the application's global state.
- When multiple components need access to the same data and should react to its changes.
- For complex logic, asynchronous actions, and state mutations.
Example of using Pinia:
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
actions: {
increment() {
this.count++
}
}
})
Summary:
- For simple cases and passing data down the tree —
provide/inject. - For complex, reactive, global state — Pinia or Vuex.