Vuex and migrating to Pinia

Intermediate · 6 min

Read a Vuex 4 store — state, getters, mutations, actions, modules — and move it to Pinia one module at a time. Vuex is in maintenance mode.

Before thisPinia fundamentalsOptions API vs Composition API

Justin Brooks · 6 min

Vuex and migrating to Pinia

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Justin BrooksReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Vuex is in maintenance mode: it still works with Vue 3, but gets no new features, and the Vue team recommends Pinia for all new work.
  • A Vuex store has one tree of state, changed only through synchronous mutations, which are triggered by commit; asynchronous work lives in actions, triggered by dispatch.
  • Large Vuex stores are split into modules, usually namespaced, so code refers to them with paths like 'cart/addItem'.
  • Each Vuex module becomes its own Pinia store; mutations disappear into actions or plain assignments, and rootState or rootGetters become direct imports of other stores.
  • Vuex and Pinia can run side by side in the same app, so a migration can move one module at a time instead of rewriting everything at once.

Why this lesson exists

If you are starting a new Vue app, use Pinia and skip this lesson. Vuex was Vue’s official store for years, but the Vue docs now state it plainly: Vuex is in maintenance mode. It still works with Vue 3, it will get no new features, and Pinia is the recommendation for new applications. Vuex 4.1.0, its most recent release, dates from October 2022. The long-planned Vuex 5 was never released; the core team decided Pinia already was the design they wanted for it.

But there is a lot of Vuex in the world. Plenty of production Vue 3 apps were built on Vuex 4 or migrated to it from Vue 2, and if you join one of those teams you will need to read it, fix it, and eventually move it. This lesson covers both.

How Vuex thinks

Vuex was designed around a strict rule borrowed from Flux and Redux: state changes go through one narrow door, so that every change can be logged and replayed. Think of it like a bank ledger. You don’t edit the balance; you write a transaction, and the balance is the result of all the transactions.

A Vuex 4 store has four parts:

// store/index.js
import { createStore } from 'vuex'

export default createStore({
  state: () => ({ items: [], loading: false }),

  getters: {
    itemCount: (state) => state.items.length,
  },

  mutations: {
    setItems(state, items) {
      state.items = items
    },
    setLoading(state, value) {
      state.loading = value
    },
  },

  actions: {
    async fetchItems({ commit }) {
      commit('setLoading', true)
      const res = await fetch('/api/cart')
      commit('setItems', await res.json())
      commit('setLoading', false)
    },
  },
})
  • State is one tree for the whole app.
  • Getters are derived values, like computed.
  • Mutations are the only sanctioned way to change state, and must be synchronous so devtools can record each change in order. You trigger them with commit('name', payload).
  • Actions hold async work and business logic. They never touch state directly; they call commit. You trigger them with dispatch('name', payload).

The store is installed with app.use(store). Components reach it through this.$store and the mapState, mapGetters, mapMutations, and mapActions helpers in the Options API, or through useStore() in the Composition API:

<script setup>
import { computed } from 'vue'
import { useStore } from 'vuex'

const store = useStore()
const count = computed(() => store.getters.itemCount)
store.dispatch('fetchItems')
</script>

Note the computed wrapper. useStore() hands back the whole store, and reading store.getters.itemCount once would give you a plain number.

Modules and string paths

One state tree gets unwieldy, so Vuex lets you split it into modules, each with its own state, getters, mutations, and actions. With namespaced: true, everything in a module is addressed by a path:

store.dispatch('cart/fetchItems')
store.commit('cart/setItems', items)
store.getters['cart/itemCount']
store.state.cart.items

Inside a module, getters and actions receive extra arguments, rootState and rootGetters, to reach other modules. Those string paths are the part of Vuex that ages worst: a typo is a silent runtime failure, and TypeScript can’t check them without a lot of extra typing work.

The same thing in Pinia

Pinia keeps the useful ideas and drops the ceremony. Here is that module as a Pinia option store:

// stores/cart.js
import { defineStore } from 'pinia'

export const useCartStore = defineStore('cart', {
  state: () => ({ items: [], loading: false }),
  getters: {
    itemCount: (state) => state.items.length,
  },
  actions: {
    async fetchItems() {
      this.loading = true
      const res = await fetch('/api/cart')
      this.items = await res.json()
      this.loading = false
    },
  },
})

What changed:

  • No mutations. Actions change state directly through this. Devtools still records every change, because Pinia tracks state reactively rather than relying on a single entry point.
  • No root store, no modules. Each module becomes its own store with its own id. Instead of rootGetters['auth/isAdmin'], you import useAuthStore and call it inside the getter or action that needs it.
  • No string paths. cart.fetchItems() is a real method call that your editor can autocomplete and TypeScript can check.
  • No context argument. Actions take their payload as normal parameters.

Migrating in practice

Pinia’s docs include a migration guide for exactly this; the order of operations that works in real codebases is:

  1. Install Pinia next to Vuex. Both can be installed on the same app at once. Nothing breaks on day one.
  2. Pick a leaf module: one that few other modules depend on.
  3. Convert it. Each module becomes a file in stores/. Turn state into a function if it isn’t already. Copy getters, replacing rootState/rootGetters with imported stores. Fold each mutation into the action that commits it, or replace it with an assignment. Drop the { commit, dispatch } context from actions.
  4. Update its consumers. Replace mapState('cart', [...]) with Pinia’s own mapState(useCartStore, [...]) in Options API components, or storeToRefs(useCartStore()) in <script setup>. Replace dispatch('cart/x') with cart.x().
  5. Delete the Vuex module, ship, repeat. When the last module is gone, remove Vuex.

If a Vuex module still needs data from an already-migrated store during the transition, an action can call the Pinia store’s use function directly, because Pinia stores work anywhere Pinia is installed.

What the video covers

Justin Brooks’s six-minute video builds a counter with Vuex 4 and covers the vocabulary a maintainer meets first: state, getters, and mutations, the map helpers in the Options API, then useStore and small helper functions in the Composition API. Actions and modules get little or no time; the sections above fill them in. It was recorded in 2020, when Vuex 4 was the official store, so it presents Vuex as the current choice. Treat it as a reading guide for legacy code, not a recommendation. The migration itself is carried by the sections above. GitLab’s walkthrough in the links below shows a real module being moved in a very large production codebase, if you want to see the process at full scale.

Where this fits

Next, data fetching in Vue turns to server data, which, as when you need a store argued, mostly shouldn’t live in a store at all.

Check yourself

  1. 01In a Vuex component you see store.commit('cart/setItems', items) in one place and store.dispatch('cart/fetchItems') in another. What is the difference?

    commit runs a mutation, which must be synchronous and is the only sanctioned way to change Vuex state. dispatch runs an action, which can be asynchronous and typically fetches data and then commits one or more mutations with the result. The 'cart/' prefix means both live in a namespaced module called cart.

  2. 02When converting a Vuex module to a Pinia store, what happens to its mutations?

    They go away as a separate concept. A mutation that just sets a field becomes a direct assignment or a $patch call, and a mutation with real logic becomes an action. Pinia actions can be synchronous or asynchronous and change state directly through this or the returned refs.

  3. 03A Vuex getter reads rootGetters['auth/isAdmin']. How is that expressed in Pinia?

    There is no root object in Pinia. The cart store imports useAuthStore and calls it inside the getter or action that needs it, then reads authStore.isAdmin directly. Dependencies between stores become ordinary imports.

  4. 04Why migrate one module at a time rather than converting the whole Vuex store in one change?

    Both libraries can be installed at once, so each module can move to Pinia, have its components updated, and ship independently. A big-bang rewrite touches every component that reads the store in one change, which is hard to review and risky to release, especially in a large codebase.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark