Search code examples
javascriptvue.jspinia

How to use Pinia in Vue 3 components correctly?


What is the correct way to use Pinia's store in Vue 3 components?

Option A

const fooStore = useFooStore();

function bar() {
  return fooStore.bar
}

const compProp = computed(() => fooStore.someProp)

Option B

function bar() {
  return useFooStore().bar
}

const compProp = computed(() => useFooStore().someProp())

Questions:

  1. Is it any difference between these 2 ways of calling the store?
  2. in the Option A – may I be sure that the values from the store are the latest?
  3. Could it be that Option B is less performant?
  4. What is the best approach?

Solution

  • It's generally a bad practice to use Vue composables in arbitrary places, they are intended to be used directly in setup block, any other usage needs to be confirmed and depends on the implementation of a composable. Pinia store composables are known to not be affected by this limitation, it's possible to use them anywhere, as long as Pinia is initialized.

    Pinia's defineStore creates store composables instead of store objects to get around circular dependencies and race conditions associated with them, this also provides a way to use custom Pinia instance. If useFooStore is used inside another store, it needs to be called directly in a place where it's used, e.g. inside action function. There is no such problem when useFooStore is used inside a component, i.e. in setup block or lifecycle hooks.

    There's no practical difference between these options. Option A is preferable because 1 useFooStore call takes less characters and resources than many of them.